1/* $FreeBSD$ */
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 <sys/stdint.h>
28#include <sys/stddef.h>
29#include <sys/param.h>
30#include <sys/queue.h>
31#include <sys/types.h>
32#include <sys/systm.h>
33#include <sys/kernel.h>
34#include <sys/bus.h>
35#include <sys/module.h>
36#include <sys/lock.h>
37#include <sys/mutex.h>
38#include <sys/condvar.h>
39#include <sys/sysctl.h>
40#include <sys/sx.h>
41#include <sys/unistd.h>
42#include <sys/callout.h>
43#include <sys/malloc.h>
44#include <sys/priv.h>
45#include <sys/proc.h>
46
47#include <dev/usb/usb.h>
48#include <dev/usb/usbdi.h>
49#include <dev/usb/usbdi_util.h>
50
51#define	USB_DEBUG_VAR usb_debug
52
53#include <dev/usb/usb_core.h>
54#include <dev/usb/usb_busdma.h>
55#include <dev/usb/usb_process.h>
56#include <dev/usb/usb_transfer.h>
57#include <dev/usb/usb_device.h>
58#include <dev/usb/usb_debug.h>
59#include <dev/usb/usb_util.h>
60
61#include <dev/usb/usb_controller.h>
62#include <dev/usb/usb_bus.h>
63#include <dev/usb/usb_pf.h>
64
65struct usb_std_packet_size {
66	struct {
67		uint16_t min;		/* inclusive */
68		uint16_t max;		/* inclusive */
69	}	range;
70
71	uint16_t fixed[4];
72};
73
74static usb_callback_t usb_request_callback;
75
76static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
77
78	/* This transfer is used for generic control endpoint transfers */
79
80	[0] = {
81		.type = UE_CONTROL,
82		.endpoint = 0x00,	/* Control endpoint */
83		.direction = UE_DIR_ANY,
84		.bufsize = USB_EP0_BUFSIZE,	/* bytes */
85		.flags = {.proxy_buffer = 1,},
86		.callback = &usb_request_callback,
87		.usb_mode = USB_MODE_DUAL,	/* both modes */
88	},
89
90	/* This transfer is used for generic clear stall only */
91
92	[1] = {
93		.type = UE_CONTROL,
94		.endpoint = 0x00,	/* Control pipe */
95		.direction = UE_DIR_ANY,
96		.bufsize = sizeof(struct usb_device_request),
97		.callback = &usb_do_clear_stall_callback,
98		.timeout = 1000,	/* 1 second */
99		.interval = 50,	/* 50ms */
100		.usb_mode = USB_MODE_HOST,
101	},
102};
103
104/* function prototypes */
105
106static void	usbd_update_max_frame_size(struct usb_xfer *);
107static void	usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
108static void	usbd_control_transfer_init(struct usb_xfer *);
109static int	usbd_setup_ctrl_transfer(struct usb_xfer *);
110static void	usb_callback_proc(struct usb_proc_msg *);
111static void	usbd_callback_ss_done_defer(struct usb_xfer *);
112static void	usbd_callback_wrapper(struct usb_xfer_queue *);
113static void	usbd_transfer_start_cb(void *);
114static uint8_t	usbd_callback_wrapper_sub(struct usb_xfer *);
115static void	usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
116		    uint8_t type, enum usb_dev_speed speed);
117
118/*------------------------------------------------------------------------*
119 *	usb_request_callback
120 *------------------------------------------------------------------------*/
121static void
122usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
123{
124	if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
125		usb_handle_request_callback(xfer, error);
126	else
127		usbd_do_request_callback(xfer, error);
128}
129
130/*------------------------------------------------------------------------*
131 *	usbd_update_max_frame_size
132 *
133 * This function updates the maximum frame size, hence high speed USB
134 * can transfer multiple consecutive packets.
135 *------------------------------------------------------------------------*/
136static void
137usbd_update_max_frame_size(struct usb_xfer *xfer)
138{
139	/* compute maximum frame size */
140	/* this computation should not overflow 16-bit */
141	/* max = 15 * 1024 */
142
143	xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
144}
145
146/*------------------------------------------------------------------------*
147 *	usbd_get_dma_delay
148 *
149 * The following function is called when we need to
150 * synchronize with DMA hardware.
151 *
152 * Returns:
153 *    0: no DMA delay required
154 * Else: milliseconds of DMA delay
155 *------------------------------------------------------------------------*/
156usb_timeout_t
157usbd_get_dma_delay(struct usb_device *udev)
158{
159	struct usb_bus_methods *mtod;
160	uint32_t temp;
161
162	mtod = udev->bus->methods;
163	temp = 0;
164
165	if (mtod->get_dma_delay) {
166		(mtod->get_dma_delay) (udev, &temp);
167		/*
168		 * Round up and convert to milliseconds. Note that we use
169		 * 1024 milliseconds per second. to save a division.
170		 */
171		temp += 0x3FF;
172		temp /= 0x400;
173	}
174	return (temp);
175}
176
177/*------------------------------------------------------------------------*
178 *	usbd_transfer_setup_sub_malloc
179 *
180 * This function will allocate one or more DMA'able memory chunks
181 * according to "size", "align" and "count" arguments. "ppc" is
182 * pointed to a linear array of USB page caches afterwards.
183 *
184 * Returns:
185 *    0: Success
186 * Else: Failure
187 *------------------------------------------------------------------------*/
188#if USB_HAVE_BUSDMA
189uint8_t
190usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
191    struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
192    usb_size_t count)
193{
194	struct usb_page_cache *pc;
195	struct usb_page *pg;
196	void *buf;
197	usb_size_t n_dma_pc;
198	usb_size_t n_obj;
199	usb_size_t x;
200	usb_size_t y;
201	usb_size_t r;
202	usb_size_t z;
203
204	USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
205	    align));
206	USB_ASSERT(size > 0, ("Invalid size = 0\n"));
207
208	if (count == 0) {
209		return (0);		/* nothing to allocate */
210	}
211	/*
212	 * Make sure that the size is aligned properly.
213	 */
214	size = -((-size) & (-align));
215
216	/*
217	 * Try multi-allocation chunks to reduce the number of DMA
218	 * allocations, hence DMA allocations are slow.
219	 */
220	if (size >= USB_PAGE_SIZE) {
221		n_dma_pc = count;
222		n_obj = 1;
223	} else {
224		/* compute number of objects per page */
225		n_obj = (USB_PAGE_SIZE / size);
226		/*
227		 * Compute number of DMA chunks, rounded up
228		 * to nearest one:
229		 */
230		n_dma_pc = ((count + n_obj - 1) / n_obj);
231	}
232
233	if (parm->buf == NULL) {
234		/* for the future */
235		parm->dma_page_ptr += n_dma_pc;
236		parm->dma_page_cache_ptr += n_dma_pc;
237		parm->dma_page_ptr += count;
238		parm->xfer_page_cache_ptr += count;
239		return (0);
240	}
241	for (x = 0; x != n_dma_pc; x++) {
242		/* need to initialize the page cache */
243		parm->dma_page_cache_ptr[x].tag_parent =
244		    &parm->curr_xfer->xroot->dma_parent_tag;
245	}
246	for (x = 0; x != count; x++) {
247		/* need to initialize the page cache */
248		parm->xfer_page_cache_ptr[x].tag_parent =
249		    &parm->curr_xfer->xroot->dma_parent_tag;
250	}
251
252	if (ppc) {
253		*ppc = parm->xfer_page_cache_ptr;
254	}
255	r = count;			/* set remainder count */
256	z = n_obj * size;		/* set allocation size */
257	pc = parm->xfer_page_cache_ptr;
258	pg = parm->dma_page_ptr;
259
260	for (x = 0; x != n_dma_pc; x++) {
261
262		if (r < n_obj) {
263			/* compute last remainder */
264			z = r * size;
265			n_obj = r;
266		}
267		if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
268		    pg, z, align)) {
269			return (1);	/* failure */
270		}
271		/* Set beginning of current buffer */
272		buf = parm->dma_page_cache_ptr->buffer;
273		/* Make room for one DMA page cache and one page */
274		parm->dma_page_cache_ptr++;
275		pg++;
276
277		for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
278
279			/* Load sub-chunk into DMA */
280			if (usb_pc_dmamap_create(pc, size)) {
281				return (1);	/* failure */
282			}
283			pc->buffer = USB_ADD_BYTES(buf, y * size);
284			pc->page_start = pg;
285
286			mtx_lock(pc->tag_parent->mtx);
287			if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
288				mtx_unlock(pc->tag_parent->mtx);
289				return (1);	/* failure */
290			}
291			mtx_unlock(pc->tag_parent->mtx);
292		}
293	}
294
295	parm->xfer_page_cache_ptr = pc;
296	parm->dma_page_ptr = pg;
297	return (0);
298}
299#endif
300
301/*------------------------------------------------------------------------*
302 *	usbd_transfer_setup_sub - transfer setup subroutine
303 *
304 * This function must be called from the "xfer_setup" callback of the
305 * USB Host or Device controller driver when setting up an USB
306 * transfer. This function will setup correct packet sizes, buffer
307 * sizes, flags and more, that are stored in the "usb_xfer"
308 * structure.
309 *------------------------------------------------------------------------*/
310void
311usbd_transfer_setup_sub(struct usb_setup_params *parm)
312{
313	enum {
314		REQ_SIZE = 8,
315		MIN_PKT = 8,
316	};
317	struct usb_xfer *xfer = parm->curr_xfer;
318	const struct usb_config *setup = parm->curr_setup;
319	struct usb_endpoint_ss_comp_descriptor *ecomp;
320	struct usb_endpoint_descriptor *edesc;
321	struct usb_std_packet_size std_size;
322	usb_frcount_t n_frlengths;
323	usb_frcount_t n_frbuffers;
324	usb_frcount_t x;
325	uint16_t maxp_old;
326	uint8_t type;
327	uint8_t zmps;
328
329	/*
330	 * Sanity check. The following parameters must be initialized before
331	 * calling this function.
332	 */
333	if ((parm->hc_max_packet_size == 0) ||
334	    (parm->hc_max_packet_count == 0) ||
335	    (parm->hc_max_frame_size == 0)) {
336		parm->err = USB_ERR_INVAL;
337		goto done;
338	}
339	edesc = xfer->endpoint->edesc;
340	ecomp = xfer->endpoint->ecomp;
341
342	type = (edesc->bmAttributes & UE_XFERTYPE);
343
344	xfer->flags = setup->flags;
345	xfer->nframes = setup->frames;
346	xfer->timeout = setup->timeout;
347	xfer->callback = setup->callback;
348	xfer->interval = setup->interval;
349	xfer->endpointno = edesc->bEndpointAddress;
350	xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
351	xfer->max_packet_count = 1;
352	/* make a shadow copy: */
353	xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
354
355	parm->bufsize = setup->bufsize;
356
357	switch (parm->speed) {
358	case USB_SPEED_HIGH:
359		switch (type) {
360		case UE_ISOCHRONOUS:
361		case UE_INTERRUPT:
362			xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
363
364			/* check for invalid max packet count */
365			if (xfer->max_packet_count > 3)
366				xfer->max_packet_count = 3;
367			break;
368		default:
369			break;
370		}
371		xfer->max_packet_size &= 0x7FF;
372		break;
373	case USB_SPEED_SUPER:
374		xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
375
376		if (ecomp != NULL)
377			xfer->max_packet_count += ecomp->bMaxBurst;
378
379		if ((xfer->max_packet_count == 0) ||
380		    (xfer->max_packet_count > 16))
381			xfer->max_packet_count = 16;
382
383		switch (type) {
384		case UE_CONTROL:
385			xfer->max_packet_count = 1;
386			break;
387		case UE_ISOCHRONOUS:
388			if (ecomp != NULL) {
389				uint8_t mult;
390
391				mult = (ecomp->bmAttributes & 3) + 1;
392				if (mult > 3)
393					mult = 3;
394
395				xfer->max_packet_count *= mult;
396			}
397			break;
398		default:
399			break;
400		}
401		xfer->max_packet_size &= 0x7FF;
402		break;
403	default:
404		break;
405	}
406	/* range check "max_packet_count" */
407
408	if (xfer->max_packet_count > parm->hc_max_packet_count) {
409		xfer->max_packet_count = parm->hc_max_packet_count;
410	}
411
412	/* store max packet size value before filtering */
413
414	maxp_old = xfer->max_packet_size;
415
416	/* filter "wMaxPacketSize" according to HC capabilities */
417
418	if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
419	    (xfer->max_packet_size == 0)) {
420		xfer->max_packet_size = parm->hc_max_packet_size;
421	}
422	/* filter "wMaxPacketSize" according to standard sizes */
423
424	usbd_get_std_packet_size(&std_size, type, parm->speed);
425
426	if (std_size.range.min || std_size.range.max) {
427
428		if (xfer->max_packet_size < std_size.range.min) {
429			xfer->max_packet_size = std_size.range.min;
430		}
431		if (xfer->max_packet_size > std_size.range.max) {
432			xfer->max_packet_size = std_size.range.max;
433		}
434	} else {
435
436		if (xfer->max_packet_size >= std_size.fixed[3]) {
437			xfer->max_packet_size = std_size.fixed[3];
438		} else if (xfer->max_packet_size >= std_size.fixed[2]) {
439			xfer->max_packet_size = std_size.fixed[2];
440		} else if (xfer->max_packet_size >= std_size.fixed[1]) {
441			xfer->max_packet_size = std_size.fixed[1];
442		} else {
443			/* only one possibility left */
444			xfer->max_packet_size = std_size.fixed[0];
445		}
446	}
447
448	/*
449	 * Check if the max packet size was outside its allowed range
450	 * and clamped to a valid value:
451	 */
452	if (maxp_old != xfer->max_packet_size)
453		xfer->flags_int.maxp_was_clamped = 1;
454
455	/* compute "max_frame_size" */
456
457	usbd_update_max_frame_size(xfer);
458
459	/* check interrupt interval and transfer pre-delay */
460
461	if (type == UE_ISOCHRONOUS) {
462
463		uint16_t frame_limit;
464
465		xfer->interval = 0;	/* not used, must be zero */
466		xfer->flags_int.isochronous_xfr = 1;	/* set flag */
467
468		if (xfer->timeout == 0) {
469			/*
470			 * set a default timeout in
471			 * case something goes wrong!
472			 */
473			xfer->timeout = 1000 / 4;
474		}
475		switch (parm->speed) {
476		case USB_SPEED_LOW:
477		case USB_SPEED_FULL:
478			frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
479			xfer->fps_shift = 0;
480			break;
481		default:
482			frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
483			xfer->fps_shift = edesc->bInterval;
484			if (xfer->fps_shift > 0)
485				xfer->fps_shift--;
486			if (xfer->fps_shift > 3)
487				xfer->fps_shift = 3;
488			if (xfer->flags.pre_scale_frames != 0)
489				xfer->nframes <<= (3 - xfer->fps_shift);
490			break;
491		}
492
493		if (xfer->nframes > frame_limit) {
494			/*
495			 * this is not going to work
496			 * cross hardware
497			 */
498			parm->err = USB_ERR_INVAL;
499			goto done;
500		}
501		if (xfer->nframes == 0) {
502			/*
503			 * this is not a valid value
504			 */
505			parm->err = USB_ERR_ZERO_NFRAMES;
506			goto done;
507		}
508	} else {
509
510		/*
511		 * If a value is specified use that else check the
512		 * endpoint descriptor!
513		 */
514		if (type == UE_INTERRUPT) {
515
516			uint32_t temp;
517
518			if (xfer->interval == 0) {
519
520				xfer->interval = edesc->bInterval;
521
522				switch (parm->speed) {
523				case USB_SPEED_LOW:
524				case USB_SPEED_FULL:
525					break;
526				default:
527					/* 125us -> 1ms */
528					if (xfer->interval < 4)
529						xfer->interval = 1;
530					else if (xfer->interval > 16)
531						xfer->interval = (1 << (16 - 4));
532					else
533						xfer->interval =
534						    (1 << (xfer->interval - 4));
535					break;
536				}
537			}
538
539			if (xfer->interval == 0) {
540				/*
541				 * One millisecond is the smallest
542				 * interval we support:
543				 */
544				xfer->interval = 1;
545			}
546
547			xfer->fps_shift = 0;
548			temp = 1;
549
550			while ((temp != 0) && (temp < xfer->interval)) {
551				xfer->fps_shift++;
552				temp *= 2;
553			}
554
555			switch (parm->speed) {
556			case USB_SPEED_LOW:
557			case USB_SPEED_FULL:
558				break;
559			default:
560				xfer->fps_shift += 3;
561				break;
562			}
563		}
564	}
565
566	/*
567	 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
568	 * to be equal to zero when setting up USB transfers, hence
569	 * this leads to alot of extra code in the USB kernel.
570	 */
571
572	if ((xfer->max_frame_size == 0) ||
573	    (xfer->max_packet_size == 0)) {
574
575		zmps = 1;
576
577		if ((parm->bufsize <= MIN_PKT) &&
578		    (type != UE_CONTROL) &&
579		    (type != UE_BULK)) {
580
581			/* workaround */
582			xfer->max_packet_size = MIN_PKT;
583			xfer->max_packet_count = 1;
584			parm->bufsize = 0;	/* automatic setup length */
585			usbd_update_max_frame_size(xfer);
586
587		} else {
588			parm->err = USB_ERR_ZERO_MAXP;
589			goto done;
590		}
591
592	} else {
593		zmps = 0;
594	}
595
596	/*
597	 * check if we should setup a default
598	 * length:
599	 */
600
601	if (parm->bufsize == 0) {
602
603		parm->bufsize = xfer->max_frame_size;
604
605		if (type == UE_ISOCHRONOUS) {
606			parm->bufsize *= xfer->nframes;
607		}
608	}
609	/*
610	 * check if we are about to setup a proxy
611	 * type of buffer:
612	 */
613
614	if (xfer->flags.proxy_buffer) {
615
616		/* round bufsize up */
617
618		parm->bufsize += (xfer->max_frame_size - 1);
619
620		if (parm->bufsize < xfer->max_frame_size) {
621			/* length wrapped around */
622			parm->err = USB_ERR_INVAL;
623			goto done;
624		}
625		/* subtract remainder */
626
627		parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
628
629		/* add length of USB device request structure, if any */
630
631		if (type == UE_CONTROL) {
632			parm->bufsize += REQ_SIZE;	/* SETUP message */
633		}
634	}
635	xfer->max_data_length = parm->bufsize;
636
637	/* Setup "n_frlengths" and "n_frbuffers" */
638
639	if (type == UE_ISOCHRONOUS) {
640		n_frlengths = xfer->nframes;
641		n_frbuffers = 1;
642	} else {
643
644		if (type == UE_CONTROL) {
645			xfer->flags_int.control_xfr = 1;
646			if (xfer->nframes == 0) {
647				if (parm->bufsize <= REQ_SIZE) {
648					/*
649					 * there will never be any data
650					 * stage
651					 */
652					xfer->nframes = 1;
653				} else {
654					xfer->nframes = 2;
655				}
656			}
657		} else {
658			if (xfer->nframes == 0) {
659				xfer->nframes = 1;
660			}
661		}
662
663		n_frlengths = xfer->nframes;
664		n_frbuffers = xfer->nframes;
665	}
666
667	/*
668	 * check if we have room for the
669	 * USB device request structure:
670	 */
671
672	if (type == UE_CONTROL) {
673
674		if (xfer->max_data_length < REQ_SIZE) {
675			/* length wrapped around or too small bufsize */
676			parm->err = USB_ERR_INVAL;
677			goto done;
678		}
679		xfer->max_data_length -= REQ_SIZE;
680	}
681	/*
682	 * Setup "frlengths" and shadow "frlengths" for keeping the
683	 * initial frame lengths when a USB transfer is complete. This
684	 * information is useful when computing isochronous offsets.
685	 */
686	xfer->frlengths = parm->xfer_length_ptr;
687	parm->xfer_length_ptr += 2 * n_frlengths;
688
689	/* setup "frbuffers" */
690	xfer->frbuffers = parm->xfer_page_cache_ptr;
691	parm->xfer_page_cache_ptr += n_frbuffers;
692
693	/* initialize max frame count */
694	xfer->max_frame_count = xfer->nframes;
695
696	/*
697	 * check if we need to setup
698	 * a local buffer:
699	 */
700
701	if (!xfer->flags.ext_buffer) {
702
703		/* align data */
704		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
705
706		if (parm->buf) {
707
708			xfer->local_buffer =
709			    USB_ADD_BYTES(parm->buf, parm->size[0]);
710
711			usbd_xfer_set_frame_offset(xfer, 0, 0);
712
713			if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
714				usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
715			}
716		}
717		parm->size[0] += parm->bufsize;
718
719		/* align data again */
720		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
721	}
722	/*
723	 * Compute maximum buffer size
724	 */
725
726	if (parm->bufsize_max < parm->bufsize) {
727		parm->bufsize_max = parm->bufsize;
728	}
729#if USB_HAVE_BUSDMA
730	if (xfer->flags_int.bdma_enable) {
731		/*
732		 * Setup "dma_page_ptr".
733		 *
734		 * Proof for formula below:
735		 *
736		 * Assume there are three USB frames having length "a", "b" and
737		 * "c". These USB frames will at maximum need "z"
738		 * "usb_page" structures. "z" is given by:
739		 *
740		 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
741		 * ((c / USB_PAGE_SIZE) + 2);
742		 *
743		 * Constraining "a", "b" and "c" like this:
744		 *
745		 * (a + b + c) <= parm->bufsize
746		 *
747		 * We know that:
748		 *
749		 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
750		 *
751		 * Here is the general formula:
752		 */
753		xfer->dma_page_ptr = parm->dma_page_ptr;
754		parm->dma_page_ptr += (2 * n_frbuffers);
755		parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
756	}
757#endif
758	if (zmps) {
759		/* correct maximum data length */
760		xfer->max_data_length = 0;
761	}
762	/* subtract USB frame remainder from "hc_max_frame_size" */
763
764	xfer->max_hc_frame_size =
765	    (parm->hc_max_frame_size -
766	    (parm->hc_max_frame_size % xfer->max_frame_size));
767
768	if (xfer->max_hc_frame_size == 0) {
769		parm->err = USB_ERR_INVAL;
770		goto done;
771	}
772
773	/* initialize frame buffers */
774
775	if (parm->buf) {
776		for (x = 0; x != n_frbuffers; x++) {
777			xfer->frbuffers[x].tag_parent =
778			    &xfer->xroot->dma_parent_tag;
779#if USB_HAVE_BUSDMA
780			if (xfer->flags_int.bdma_enable &&
781			    (parm->bufsize_max > 0)) {
782
783				if (usb_pc_dmamap_create(
784				    xfer->frbuffers + x,
785				    parm->bufsize_max)) {
786					parm->err = USB_ERR_NOMEM;
787					goto done;
788				}
789			}
790#endif
791		}
792	}
793done:
794	if (parm->err) {
795		/*
796		 * Set some dummy values so that we avoid division by zero:
797		 */
798		xfer->max_hc_frame_size = 1;
799		xfer->max_frame_size = 1;
800		xfer->max_packet_size = 1;
801		xfer->max_data_length = 0;
802		xfer->nframes = 0;
803		xfer->max_frame_count = 0;
804	}
805}
806
807/*------------------------------------------------------------------------*
808 *	usbd_transfer_setup - setup an array of USB transfers
809 *
810 * NOTE: You must always call "usbd_transfer_unsetup" after calling
811 * "usbd_transfer_setup" if success was returned.
812 *
813 * The idea is that the USB device driver should pre-allocate all its
814 * transfers by one call to this function.
815 *
816 * Return values:
817 *    0: Success
818 * Else: Failure
819 *------------------------------------------------------------------------*/
820usb_error_t
821usbd_transfer_setup(struct usb_device *udev,
822    const uint8_t *ifaces, struct usb_xfer **ppxfer,
823    const struct usb_config *setup_start, uint16_t n_setup,
824    void *priv_sc, struct mtx *xfer_mtx)
825{
826	const struct usb_config *setup_end = setup_start + n_setup;
827	const struct usb_config *setup;
828	struct usb_setup_params *parm;
829	struct usb_endpoint *ep;
830	struct usb_xfer_root *info;
831	struct usb_xfer *xfer;
832	void *buf = NULL;
833	usb_error_t error = 0;
834	uint16_t n;
835	uint16_t refcount;
836	uint8_t do_unlock;
837
838	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
839	    "usbd_transfer_setup can sleep!");
840
841	/* do some checking first */
842
843	if (n_setup == 0) {
844		DPRINTFN(6, "setup array has zero length!\n");
845		return (USB_ERR_INVAL);
846	}
847	if (ifaces == 0) {
848		DPRINTFN(6, "ifaces array is NULL!\n");
849		return (USB_ERR_INVAL);
850	}
851	if (xfer_mtx == NULL) {
852		DPRINTFN(6, "using global lock\n");
853		xfer_mtx = &Giant;
854	}
855
856	/* more sanity checks */
857
858	for (setup = setup_start, n = 0;
859	    setup != setup_end; setup++, n++) {
860		if (setup->bufsize == (usb_frlength_t)-1) {
861			error = USB_ERR_BAD_BUFSIZE;
862			DPRINTF("invalid bufsize\n");
863		}
864		if (setup->callback == NULL) {
865			error = USB_ERR_NO_CALLBACK;
866			DPRINTF("no callback\n");
867		}
868		ppxfer[n] = NULL;
869	}
870
871	if (error)
872		return (error);
873
874	/* Protect scratch area */
875	do_unlock = usbd_enum_lock(udev);
876
877	refcount = 0;
878	info = NULL;
879
880	parm = &udev->scratch.xfer_setup[0].parm;
881	memset(parm, 0, sizeof(*parm));
882
883	parm->udev = udev;
884	parm->speed = usbd_get_speed(udev);
885	parm->hc_max_packet_count = 1;
886
887	if (parm->speed >= USB_SPEED_MAX) {
888		parm->err = USB_ERR_INVAL;
889		goto done;
890	}
891	/* setup all transfers */
892
893	while (1) {
894
895		if (buf) {
896			/*
897			 * Initialize the "usb_xfer_root" structure,
898			 * which is common for all our USB transfers.
899			 */
900			info = USB_ADD_BYTES(buf, 0);
901
902			info->memory_base = buf;
903			info->memory_size = parm->size[0];
904
905#if USB_HAVE_BUSDMA
906			info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
907			info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
908#endif
909			info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
910			info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
911
912			cv_init(&info->cv_drain, "WDRAIN");
913
914			info->xfer_mtx = xfer_mtx;
915#if USB_HAVE_BUSDMA
916			usb_dma_tag_setup(&info->dma_parent_tag,
917			    parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
918			    xfer_mtx, &usb_bdma_done_event, 32, parm->dma_tag_max);
919#endif
920
921			info->bus = udev->bus;
922			info->udev = udev;
923
924			TAILQ_INIT(&info->done_q.head);
925			info->done_q.command = &usbd_callback_wrapper;
926#if USB_HAVE_BUSDMA
927			TAILQ_INIT(&info->dma_q.head);
928			info->dma_q.command = &usb_bdma_work_loop;
929#endif
930			info->done_m[0].hdr.pm_callback = &usb_callback_proc;
931			info->done_m[0].xroot = info;
932			info->done_m[1].hdr.pm_callback = &usb_callback_proc;
933			info->done_m[1].xroot = info;
934
935			/*
936			 * In device side mode control endpoint
937			 * requests need to run from a separate
938			 * context, else there is a chance of
939			 * deadlock!
940			 */
941			if (setup_start == usb_control_ep_cfg)
942				info->done_p =
943				    &udev->bus->control_xfer_proc;
944			else if (xfer_mtx == &Giant)
945				info->done_p =
946				    &udev->bus->giant_callback_proc;
947			else
948				info->done_p =
949				    &udev->bus->non_giant_callback_proc;
950		}
951		/* reset sizes */
952
953		parm->size[0] = 0;
954		parm->buf = buf;
955		parm->size[0] += sizeof(info[0]);
956
957		for (setup = setup_start, n = 0;
958		    setup != setup_end; setup++, n++) {
959
960			/* skip USB transfers without callbacks: */
961			if (setup->callback == NULL) {
962				continue;
963			}
964			/* see if there is a matching endpoint */
965			ep = usbd_get_endpoint(udev,
966			    ifaces[setup->if_index], setup);
967
968			if ((ep == NULL) || (ep->methods == NULL)) {
969				if (setup->flags.no_pipe_ok)
970					continue;
971				if ((setup->usb_mode != USB_MODE_DUAL) &&
972				    (setup->usb_mode != udev->flags.usb_mode))
973					continue;
974				parm->err = USB_ERR_NO_PIPE;
975				goto done;
976			}
977
978			/* align data properly */
979			parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
980
981			/* store current setup pointer */
982			parm->curr_setup = setup;
983
984			if (buf) {
985				/*
986				 * Common initialization of the
987				 * "usb_xfer" structure.
988				 */
989				xfer = USB_ADD_BYTES(buf, parm->size[0]);
990				xfer->address = udev->address;
991				xfer->priv_sc = priv_sc;
992				xfer->xroot = info;
993
994				usb_callout_init_mtx(&xfer->timeout_handle,
995				    &udev->bus->bus_mtx, 0);
996			} else {
997				/*
998				 * Setup a dummy xfer, hence we are
999				 * writing to the "usb_xfer"
1000				 * structure pointed to by "xfer"
1001				 * before we have allocated any
1002				 * memory:
1003				 */
1004				xfer = &udev->scratch.xfer_setup[0].dummy;
1005				memset(xfer, 0, sizeof(*xfer));
1006				refcount++;
1007			}
1008
1009			/* set transfer endpoint pointer */
1010			xfer->endpoint = ep;
1011
1012			parm->size[0] += sizeof(xfer[0]);
1013			parm->methods = xfer->endpoint->methods;
1014			parm->curr_xfer = xfer;
1015
1016			/*
1017			 * Call the Host or Device controller transfer
1018			 * setup routine:
1019			 */
1020			(udev->bus->methods->xfer_setup) (parm);
1021
1022			/* check for error */
1023			if (parm->err)
1024				goto done;
1025
1026			if (buf) {
1027				/*
1028				 * Increment the endpoint refcount. This
1029				 * basically prevents setting a new
1030				 * configuration and alternate setting
1031				 * when USB transfers are in use on
1032				 * the given interface. Search the USB
1033				 * code for "endpoint->refcount_alloc" if you
1034				 * want more information.
1035				 */
1036				USB_BUS_LOCK(info->bus);
1037				if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1038					parm->err = USB_ERR_INVAL;
1039
1040				xfer->endpoint->refcount_alloc++;
1041
1042				if (xfer->endpoint->refcount_alloc == 0)
1043					panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1044				USB_BUS_UNLOCK(info->bus);
1045
1046				/*
1047				 * Whenever we set ppxfer[] then we
1048				 * also need to increment the
1049				 * "setup_refcount":
1050				 */
1051				info->setup_refcount++;
1052
1053				/*
1054				 * Transfer is successfully setup and
1055				 * can be used:
1056				 */
1057				ppxfer[n] = xfer;
1058			}
1059
1060			/* check for error */
1061			if (parm->err)
1062				goto done;
1063		}
1064
1065		if (buf != NULL || parm->err != 0)
1066			goto done;
1067
1068		/* if no transfers, nothing to do */
1069		if (refcount == 0)
1070			goto done;
1071
1072		/* align data properly */
1073		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1074
1075		/* store offset temporarily */
1076		parm->size[1] = parm->size[0];
1077
1078		/*
1079		 * The number of DMA tags required depends on
1080		 * the number of endpoints. The current estimate
1081		 * for maximum number of DMA tags per endpoint
1082		 * is two.
1083		 */
1084		parm->dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1085
1086		/*
1087		 * DMA tags for QH, TD, Data and more.
1088		 */
1089		parm->dma_tag_max += 8;
1090
1091		parm->dma_tag_p += parm->dma_tag_max;
1092
1093		parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1094		    ((uint8_t *)0);
1095
1096		/* align data properly */
1097		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1098
1099		/* store offset temporarily */
1100		parm->size[3] = parm->size[0];
1101
1102		parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1103		    ((uint8_t *)0);
1104
1105		/* align data properly */
1106		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1107
1108		/* store offset temporarily */
1109		parm->size[4] = parm->size[0];
1110
1111		parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1112		    ((uint8_t *)0);
1113
1114		/* store end offset temporarily */
1115		parm->size[5] = parm->size[0];
1116
1117		parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1118		    ((uint8_t *)0);
1119
1120		/* store end offset temporarily */
1121
1122		parm->size[2] = parm->size[0];
1123
1124		/* align data properly */
1125		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1126
1127		parm->size[6] = parm->size[0];
1128
1129		parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1130		    ((uint8_t *)0);
1131
1132		/* align data properly */
1133		parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1134
1135		/* allocate zeroed memory */
1136		buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1137
1138		if (buf == NULL) {
1139			parm->err = USB_ERR_NOMEM;
1140			DPRINTFN(0, "cannot allocate memory block for "
1141			    "configuration (%d bytes)\n",
1142			    parm->size[0]);
1143			goto done;
1144		}
1145		parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1146		parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1147		parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1148		parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1149		parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1150	}
1151
1152done:
1153	if (buf) {
1154		if (info->setup_refcount == 0) {
1155			/*
1156			 * "usbd_transfer_unsetup_sub" will unlock
1157			 * the bus mutex before returning !
1158			 */
1159			USB_BUS_LOCK(info->bus);
1160
1161			/* something went wrong */
1162			usbd_transfer_unsetup_sub(info, 0);
1163		}
1164	}
1165
1166	/* check if any errors happened */
1167	if (parm->err)
1168		usbd_transfer_unsetup(ppxfer, n_setup);
1169
1170	error = parm->err;
1171
1172	if (do_unlock)
1173		usbd_enum_unlock(udev);
1174
1175	return (error);
1176}
1177
1178/*------------------------------------------------------------------------*
1179 *	usbd_transfer_unsetup_sub - factored out code
1180 *------------------------------------------------------------------------*/
1181static void
1182usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1183{
1184#if USB_HAVE_BUSDMA
1185	struct usb_page_cache *pc;
1186#endif
1187
1188	USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1189
1190	/* wait for any outstanding DMA operations */
1191
1192	if (needs_delay) {
1193		usb_timeout_t temp;
1194		temp = usbd_get_dma_delay(info->udev);
1195		if (temp != 0) {
1196			usb_pause_mtx(&info->bus->bus_mtx,
1197			    USB_MS_TO_TICKS(temp));
1198		}
1199	}
1200
1201	/* make sure that our done messages are not queued anywhere */
1202	usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1203
1204	USB_BUS_UNLOCK(info->bus);
1205
1206#if USB_HAVE_BUSDMA
1207	/* free DMA'able memory, if any */
1208	pc = info->dma_page_cache_start;
1209	while (pc != info->dma_page_cache_end) {
1210		usb_pc_free_mem(pc);
1211		pc++;
1212	}
1213
1214	/* free DMA maps in all "xfer->frbuffers" */
1215	pc = info->xfer_page_cache_start;
1216	while (pc != info->xfer_page_cache_end) {
1217		usb_pc_dmamap_destroy(pc);
1218		pc++;
1219	}
1220
1221	/* free all DMA tags */
1222	usb_dma_tag_unsetup(&info->dma_parent_tag);
1223#endif
1224
1225	cv_destroy(&info->cv_drain);
1226
1227	/*
1228	 * free the "memory_base" last, hence the "info" structure is
1229	 * contained within the "memory_base"!
1230	 */
1231	free(info->memory_base, M_USB);
1232}
1233
1234/*------------------------------------------------------------------------*
1235 *	usbd_transfer_unsetup - unsetup/free an array of USB transfers
1236 *
1237 * NOTE: All USB transfers in progress will get called back passing
1238 * the error code "USB_ERR_CANCELLED" before this function
1239 * returns.
1240 *------------------------------------------------------------------------*/
1241void
1242usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1243{
1244	struct usb_xfer *xfer;
1245	struct usb_xfer_root *info;
1246	uint8_t needs_delay = 0;
1247
1248	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1249	    "usbd_transfer_unsetup can sleep!");
1250
1251	while (n_setup--) {
1252		xfer = pxfer[n_setup];
1253
1254		if (xfer == NULL)
1255			continue;
1256
1257		info = xfer->xroot;
1258
1259		USB_XFER_LOCK(xfer);
1260		USB_BUS_LOCK(info->bus);
1261
1262		/*
1263		 * HINT: when you start/stop a transfer, it might be a
1264		 * good idea to directly use the "pxfer[]" structure:
1265		 *
1266		 * usbd_transfer_start(sc->pxfer[0]);
1267		 * usbd_transfer_stop(sc->pxfer[0]);
1268		 *
1269		 * That way, if your code has many parts that will not
1270		 * stop running under the same lock, in other words
1271		 * "xfer_mtx", the usbd_transfer_start and
1272		 * usbd_transfer_stop functions will simply return
1273		 * when they detect a NULL pointer argument.
1274		 *
1275		 * To avoid any races we clear the "pxfer[]" pointer
1276		 * while holding the private mutex of the driver:
1277		 */
1278		pxfer[n_setup] = NULL;
1279
1280		USB_BUS_UNLOCK(info->bus);
1281		USB_XFER_UNLOCK(xfer);
1282
1283		usbd_transfer_drain(xfer);
1284
1285#if USB_HAVE_BUSDMA
1286		if (xfer->flags_int.bdma_enable)
1287			needs_delay = 1;
1288#endif
1289		/*
1290		 * NOTE: default endpoint does not have an
1291		 * interface, even if endpoint->iface_index == 0
1292		 */
1293		USB_BUS_LOCK(info->bus);
1294		xfer->endpoint->refcount_alloc--;
1295		USB_BUS_UNLOCK(info->bus);
1296
1297		usb_callout_drain(&xfer->timeout_handle);
1298
1299		USB_BUS_LOCK(info->bus);
1300
1301		USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1302		    "reference count\n"));
1303
1304		info->setup_refcount--;
1305
1306		if (info->setup_refcount == 0) {
1307			usbd_transfer_unsetup_sub(info,
1308			    needs_delay);
1309		} else {
1310			USB_BUS_UNLOCK(info->bus);
1311		}
1312	}
1313}
1314
1315/*------------------------------------------------------------------------*
1316 *	usbd_control_transfer_init - factored out code
1317 *
1318 * In USB Device Mode we have to wait for the SETUP packet which
1319 * containst the "struct usb_device_request" structure, before we can
1320 * transfer any data. In USB Host Mode we already have the SETUP
1321 * packet at the moment the USB transfer is started. This leads us to
1322 * having to setup the USB transfer at two different places in
1323 * time. This function just contains factored out control transfer
1324 * initialisation code, so that we don't duplicate the code.
1325 *------------------------------------------------------------------------*/
1326static void
1327usbd_control_transfer_init(struct usb_xfer *xfer)
1328{
1329	struct usb_device_request req;
1330
1331	/* copy out the USB request header */
1332
1333	usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1334
1335	/* setup remainder */
1336
1337	xfer->flags_int.control_rem = UGETW(req.wLength);
1338
1339	/* copy direction to endpoint variable */
1340
1341	xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1342	xfer->endpointno |=
1343	    (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1344}
1345
1346/*------------------------------------------------------------------------*
1347 *	usbd_setup_ctrl_transfer
1348 *
1349 * This function handles initialisation of control transfers. Control
1350 * transfers are special in that regard that they can both transmit
1351 * and receive data.
1352 *
1353 * Return values:
1354 *    0: Success
1355 * Else: Failure
1356 *------------------------------------------------------------------------*/
1357static int
1358usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1359{
1360	usb_frlength_t len;
1361
1362	/* Check for control endpoint stall */
1363	if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1364		/* the control transfer is no longer active */
1365		xfer->flags_int.control_stall = 1;
1366		xfer->flags_int.control_act = 0;
1367	} else {
1368		/* don't stall control transfer by default */
1369		xfer->flags_int.control_stall = 0;
1370	}
1371
1372	/* Check for invalid number of frames */
1373	if (xfer->nframes > 2) {
1374		/*
1375		 * If you need to split a control transfer, you
1376		 * have to do one part at a time. Only with
1377		 * non-control transfers you can do multiple
1378		 * parts a time.
1379		 */
1380		DPRINTFN(0, "Too many frames: %u\n",
1381		    (unsigned int)xfer->nframes);
1382		goto error;
1383	}
1384
1385	/*
1386         * Check if there is a control
1387         * transfer in progress:
1388         */
1389	if (xfer->flags_int.control_act) {
1390
1391		if (xfer->flags_int.control_hdr) {
1392
1393			/* clear send header flag */
1394
1395			xfer->flags_int.control_hdr = 0;
1396
1397			/* setup control transfer */
1398			if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1399				usbd_control_transfer_init(xfer);
1400			}
1401		}
1402		/* get data length */
1403
1404		len = xfer->sumlen;
1405
1406	} else {
1407
1408		/* the size of the SETUP structure is hardcoded ! */
1409
1410		if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1411			DPRINTFN(0, "Wrong framelength %u != %zu\n",
1412			    xfer->frlengths[0], sizeof(struct
1413			    usb_device_request));
1414			goto error;
1415		}
1416		/* check USB mode */
1417		if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1418
1419			/* check number of frames */
1420			if (xfer->nframes != 1) {
1421				/*
1422			         * We need to receive the setup
1423			         * message first so that we know the
1424			         * data direction!
1425			         */
1426				DPRINTF("Misconfigured transfer\n");
1427				goto error;
1428			}
1429			/*
1430			 * Set a dummy "control_rem" value.  This
1431			 * variable will be overwritten later by a
1432			 * call to "usbd_control_transfer_init()" !
1433			 */
1434			xfer->flags_int.control_rem = 0xFFFF;
1435		} else {
1436
1437			/* setup "endpoint" and "control_rem" */
1438
1439			usbd_control_transfer_init(xfer);
1440		}
1441
1442		/* set transfer-header flag */
1443
1444		xfer->flags_int.control_hdr = 1;
1445
1446		/* get data length */
1447
1448		len = (xfer->sumlen - sizeof(struct usb_device_request));
1449	}
1450
1451	/* check if there is a length mismatch */
1452
1453	if (len > xfer->flags_int.control_rem) {
1454		DPRINTFN(0, "Length (%d) greater than "
1455		    "remaining length (%d)\n", len,
1456		    xfer->flags_int.control_rem);
1457		goto error;
1458	}
1459	/* check if we are doing a short transfer */
1460
1461	if (xfer->flags.force_short_xfer) {
1462		xfer->flags_int.control_rem = 0;
1463	} else {
1464		if ((len != xfer->max_data_length) &&
1465		    (len != xfer->flags_int.control_rem) &&
1466		    (xfer->nframes != 1)) {
1467			DPRINTFN(0, "Short control transfer without "
1468			    "force_short_xfer set\n");
1469			goto error;
1470		}
1471		xfer->flags_int.control_rem -= len;
1472	}
1473
1474	/* the status part is executed when "control_act" is 0 */
1475
1476	if ((xfer->flags_int.control_rem > 0) ||
1477	    (xfer->flags.manual_status)) {
1478		/* don't execute the STATUS stage yet */
1479		xfer->flags_int.control_act = 1;
1480
1481		/* sanity check */
1482		if ((!xfer->flags_int.control_hdr) &&
1483		    (xfer->nframes == 1)) {
1484			/*
1485		         * This is not a valid operation!
1486		         */
1487			DPRINTFN(0, "Invalid parameter "
1488			    "combination\n");
1489			goto error;
1490		}
1491	} else {
1492		/* time to execute the STATUS stage */
1493		xfer->flags_int.control_act = 0;
1494	}
1495	return (0);			/* success */
1496
1497error:
1498	return (1);			/* failure */
1499}
1500
1501/*------------------------------------------------------------------------*
1502 *	usbd_transfer_submit - start USB hardware for the given transfer
1503 *
1504 * This function should only be called from the USB callback.
1505 *------------------------------------------------------------------------*/
1506void
1507usbd_transfer_submit(struct usb_xfer *xfer)
1508{
1509	struct usb_xfer_root *info;
1510	struct usb_bus *bus;
1511	usb_frcount_t x;
1512
1513	info = xfer->xroot;
1514	bus = info->bus;
1515
1516	DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1517	    xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1518	    "read" : "write");
1519
1520#ifdef USB_DEBUG
1521	if (USB_DEBUG_VAR > 0) {
1522		USB_BUS_LOCK(bus);
1523
1524		usb_dump_endpoint(xfer->endpoint);
1525
1526		USB_BUS_UNLOCK(bus);
1527	}
1528#endif
1529
1530	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1531	USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1532
1533	/* Only open the USB transfer once! */
1534	if (!xfer->flags_int.open) {
1535		xfer->flags_int.open = 1;
1536
1537		DPRINTF("open\n");
1538
1539		USB_BUS_LOCK(bus);
1540		(xfer->endpoint->methods->open) (xfer);
1541		USB_BUS_UNLOCK(bus);
1542	}
1543	/* set "transferring" flag */
1544	xfer->flags_int.transferring = 1;
1545
1546#if USB_HAVE_POWERD
1547	/* increment power reference */
1548	usbd_transfer_power_ref(xfer, 1);
1549#endif
1550	/*
1551	 * Check if the transfer is waiting on a queue, most
1552	 * frequently the "done_q":
1553	 */
1554	if (xfer->wait_queue) {
1555		USB_BUS_LOCK(bus);
1556		usbd_transfer_dequeue(xfer);
1557		USB_BUS_UNLOCK(bus);
1558	}
1559	/* clear "did_dma_delay" flag */
1560	xfer->flags_int.did_dma_delay = 0;
1561
1562	/* clear "did_close" flag */
1563	xfer->flags_int.did_close = 0;
1564
1565#if USB_HAVE_BUSDMA
1566	/* clear "bdma_setup" flag */
1567	xfer->flags_int.bdma_setup = 0;
1568#endif
1569	/* by default we cannot cancel any USB transfer immediately */
1570	xfer->flags_int.can_cancel_immed = 0;
1571
1572	/* clear lengths and frame counts by default */
1573	xfer->sumlen = 0;
1574	xfer->actlen = 0;
1575	xfer->aframes = 0;
1576
1577	/* clear any previous errors */
1578	xfer->error = 0;
1579
1580	/* Check if the device is still alive */
1581	if (info->udev->state < USB_STATE_POWERED) {
1582		USB_BUS_LOCK(bus);
1583		/*
1584		 * Must return cancelled error code else
1585		 * device drivers can hang.
1586		 */
1587		usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1588		USB_BUS_UNLOCK(bus);
1589		return;
1590	}
1591
1592	/* sanity check */
1593	if (xfer->nframes == 0) {
1594		if (xfer->flags.stall_pipe) {
1595			/*
1596			 * Special case - want to stall without transferring
1597			 * any data:
1598			 */
1599			DPRINTF("xfer=%p nframes=0: stall "
1600			    "or clear stall!\n", xfer);
1601			USB_BUS_LOCK(bus);
1602			xfer->flags_int.can_cancel_immed = 1;
1603			/* start the transfer */
1604			usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1605			USB_BUS_UNLOCK(bus);
1606			return;
1607		}
1608		USB_BUS_LOCK(bus);
1609		usbd_transfer_done(xfer, USB_ERR_INVAL);
1610		USB_BUS_UNLOCK(bus);
1611		return;
1612	}
1613	/* compute some variables */
1614
1615	for (x = 0; x != xfer->nframes; x++) {
1616		/* make a copy of the frlenghts[] */
1617		xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1618		/* compute total transfer length */
1619		xfer->sumlen += xfer->frlengths[x];
1620		if (xfer->sumlen < xfer->frlengths[x]) {
1621			/* length wrapped around */
1622			USB_BUS_LOCK(bus);
1623			usbd_transfer_done(xfer, USB_ERR_INVAL);
1624			USB_BUS_UNLOCK(bus);
1625			return;
1626		}
1627	}
1628
1629	/* clear some internal flags */
1630
1631	xfer->flags_int.short_xfer_ok = 0;
1632	xfer->flags_int.short_frames_ok = 0;
1633
1634	/* check if this is a control transfer */
1635
1636	if (xfer->flags_int.control_xfr) {
1637
1638		if (usbd_setup_ctrl_transfer(xfer)) {
1639			USB_BUS_LOCK(bus);
1640			usbd_transfer_done(xfer, USB_ERR_STALLED);
1641			USB_BUS_UNLOCK(bus);
1642			return;
1643		}
1644	}
1645	/*
1646	 * Setup filtered version of some transfer flags,
1647	 * in case of data read direction
1648	 */
1649	if (USB_GET_DATA_ISREAD(xfer)) {
1650
1651		if (xfer->flags.short_frames_ok) {
1652			xfer->flags_int.short_xfer_ok = 1;
1653			xfer->flags_int.short_frames_ok = 1;
1654		} else if (xfer->flags.short_xfer_ok) {
1655			xfer->flags_int.short_xfer_ok = 1;
1656
1657			/* check for control transfer */
1658			if (xfer->flags_int.control_xfr) {
1659				/*
1660				 * 1) Control transfers do not support
1661				 * reception of multiple short USB
1662				 * frames in host mode and device side
1663				 * mode, with exception of:
1664				 *
1665				 * 2) Due to sometimes buggy device
1666				 * side firmware we need to do a
1667				 * STATUS stage in case of short
1668				 * control transfers in USB host mode.
1669				 * The STATUS stage then becomes the
1670				 * "alt_next" to the DATA stage.
1671				 */
1672				xfer->flags_int.short_frames_ok = 1;
1673			}
1674		}
1675	}
1676	/*
1677	 * Check if BUS-DMA support is enabled and try to load virtual
1678	 * buffers into DMA, if any:
1679	 */
1680#if USB_HAVE_BUSDMA
1681	if (xfer->flags_int.bdma_enable) {
1682		/* insert the USB transfer last in the BUS-DMA queue */
1683		usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1684		return;
1685	}
1686#endif
1687	/*
1688	 * Enter the USB transfer into the Host Controller or
1689	 * Device Controller schedule:
1690	 */
1691	usbd_pipe_enter(xfer);
1692}
1693
1694/*------------------------------------------------------------------------*
1695 *	usbd_pipe_enter - factored out code
1696 *------------------------------------------------------------------------*/
1697void
1698usbd_pipe_enter(struct usb_xfer *xfer)
1699{
1700	struct usb_endpoint *ep;
1701
1702	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1703
1704	USB_BUS_LOCK(xfer->xroot->bus);
1705
1706	ep = xfer->endpoint;
1707
1708	DPRINTF("enter\n");
1709
1710	/* the transfer can now be cancelled */
1711	xfer->flags_int.can_cancel_immed = 1;
1712
1713	/* enter the transfer */
1714	(ep->methods->enter) (xfer);
1715
1716	/* check for transfer error */
1717	if (xfer->error) {
1718		/* some error has happened */
1719		usbd_transfer_done(xfer, 0);
1720		USB_BUS_UNLOCK(xfer->xroot->bus);
1721		return;
1722	}
1723
1724	/* start the transfer */
1725	usb_command_wrapper(&ep->endpoint_q, xfer);
1726	USB_BUS_UNLOCK(xfer->xroot->bus);
1727}
1728
1729/*------------------------------------------------------------------------*
1730 *	usbd_transfer_start - start an USB transfer
1731 *
1732 * NOTE: Calling this function more than one time will only
1733 *       result in a single transfer start, until the USB transfer
1734 *       completes.
1735 *------------------------------------------------------------------------*/
1736void
1737usbd_transfer_start(struct usb_xfer *xfer)
1738{
1739	if (xfer == NULL) {
1740		/* transfer is gone */
1741		return;
1742	}
1743	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1744
1745	/* mark the USB transfer started */
1746
1747	if (!xfer->flags_int.started) {
1748		/* lock the BUS lock to avoid races updating flags_int */
1749		USB_BUS_LOCK(xfer->xroot->bus);
1750		xfer->flags_int.started = 1;
1751		USB_BUS_UNLOCK(xfer->xroot->bus);
1752	}
1753	/* check if the USB transfer callback is already transferring */
1754
1755	if (xfer->flags_int.transferring) {
1756		return;
1757	}
1758	USB_BUS_LOCK(xfer->xroot->bus);
1759	/* call the USB transfer callback */
1760	usbd_callback_ss_done_defer(xfer);
1761	USB_BUS_UNLOCK(xfer->xroot->bus);
1762}
1763
1764/*------------------------------------------------------------------------*
1765 *	usbd_transfer_stop - stop an USB transfer
1766 *
1767 * NOTE: Calling this function more than one time will only
1768 *       result in a single transfer stop.
1769 * NOTE: When this function returns it is not safe to free nor
1770 *       reuse any DMA buffers. See "usbd_transfer_drain()".
1771 *------------------------------------------------------------------------*/
1772void
1773usbd_transfer_stop(struct usb_xfer *xfer)
1774{
1775	struct usb_endpoint *ep;
1776
1777	if (xfer == NULL) {
1778		/* transfer is gone */
1779		return;
1780	}
1781	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1782
1783	/* check if the USB transfer was ever opened */
1784
1785	if (!xfer->flags_int.open) {
1786		if (xfer->flags_int.started) {
1787			/* nothing to do except clearing the "started" flag */
1788			/* lock the BUS lock to avoid races updating flags_int */
1789			USB_BUS_LOCK(xfer->xroot->bus);
1790			xfer->flags_int.started = 0;
1791			USB_BUS_UNLOCK(xfer->xroot->bus);
1792		}
1793		return;
1794	}
1795	/* try to stop the current USB transfer */
1796
1797	USB_BUS_LOCK(xfer->xroot->bus);
1798	/* override any previous error */
1799	xfer->error = USB_ERR_CANCELLED;
1800
1801	/*
1802	 * Clear "open" and "started" when both private and USB lock
1803	 * is locked so that we don't get a race updating "flags_int"
1804	 */
1805	xfer->flags_int.open = 0;
1806	xfer->flags_int.started = 0;
1807
1808	/*
1809	 * Check if we can cancel the USB transfer immediately.
1810	 */
1811	if (xfer->flags_int.transferring) {
1812		if (xfer->flags_int.can_cancel_immed &&
1813		    (!xfer->flags_int.did_close)) {
1814			DPRINTF("close\n");
1815			/*
1816			 * The following will lead to an USB_ERR_CANCELLED
1817			 * error code being passed to the USB callback.
1818			 */
1819			(xfer->endpoint->methods->close) (xfer);
1820			/* only close once */
1821			xfer->flags_int.did_close = 1;
1822		} else {
1823			/* need to wait for the next done callback */
1824		}
1825	} else {
1826		DPRINTF("close\n");
1827
1828		/* close here and now */
1829		(xfer->endpoint->methods->close) (xfer);
1830
1831		/*
1832		 * Any additional DMA delay is done by
1833		 * "usbd_transfer_unsetup()".
1834		 */
1835
1836		/*
1837		 * Special case. Check if we need to restart a blocked
1838		 * endpoint.
1839		 */
1840		ep = xfer->endpoint;
1841
1842		/*
1843		 * If the current USB transfer is completing we need
1844		 * to start the next one:
1845		 */
1846		if (ep->endpoint_q.curr == xfer) {
1847			usb_command_wrapper(&ep->endpoint_q, NULL);
1848		}
1849	}
1850
1851	USB_BUS_UNLOCK(xfer->xroot->bus);
1852}
1853
1854/*------------------------------------------------------------------------*
1855 *	usbd_transfer_pending
1856 *
1857 * This function will check if an USB transfer is pending which is a
1858 * little bit complicated!
1859 * Return values:
1860 * 0: Not pending
1861 * 1: Pending: The USB transfer will receive a callback in the future.
1862 *------------------------------------------------------------------------*/
1863uint8_t
1864usbd_transfer_pending(struct usb_xfer *xfer)
1865{
1866	struct usb_xfer_root *info;
1867	struct usb_xfer_queue *pq;
1868
1869	if (xfer == NULL) {
1870		/* transfer is gone */
1871		return (0);
1872	}
1873	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1874
1875	if (xfer->flags_int.transferring) {
1876		/* trivial case */
1877		return (1);
1878	}
1879	USB_BUS_LOCK(xfer->xroot->bus);
1880	if (xfer->wait_queue) {
1881		/* we are waiting on a queue somewhere */
1882		USB_BUS_UNLOCK(xfer->xroot->bus);
1883		return (1);
1884	}
1885	info = xfer->xroot;
1886	pq = &info->done_q;
1887
1888	if (pq->curr == xfer) {
1889		/* we are currently scheduled for callback */
1890		USB_BUS_UNLOCK(xfer->xroot->bus);
1891		return (1);
1892	}
1893	/* we are not pending */
1894	USB_BUS_UNLOCK(xfer->xroot->bus);
1895	return (0);
1896}
1897
1898/*------------------------------------------------------------------------*
1899 *	usbd_transfer_drain
1900 *
1901 * This function will stop the USB transfer and wait for any
1902 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1903 * are loaded into DMA can safely be freed or reused after that this
1904 * function has returned.
1905 *------------------------------------------------------------------------*/
1906void
1907usbd_transfer_drain(struct usb_xfer *xfer)
1908{
1909	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1910	    "usbd_transfer_drain can sleep!");
1911
1912	if (xfer == NULL) {
1913		/* transfer is gone */
1914		return;
1915	}
1916	if (xfer->xroot->xfer_mtx != &Giant) {
1917		USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1918	}
1919	USB_XFER_LOCK(xfer);
1920
1921	usbd_transfer_stop(xfer);
1922
1923	while (usbd_transfer_pending(xfer) ||
1924	    xfer->flags_int.doing_callback) {
1925
1926		/*
1927		 * It is allowed that the callback can drop its
1928		 * transfer mutex. In that case checking only
1929		 * "usbd_transfer_pending()" is not enough to tell if
1930		 * the USB transfer is fully drained. We also need to
1931		 * check the internal "doing_callback" flag.
1932		 */
1933		xfer->flags_int.draining = 1;
1934
1935		/*
1936		 * Wait until the current outstanding USB
1937		 * transfer is complete !
1938		 */
1939		cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1940	}
1941	USB_XFER_UNLOCK(xfer);
1942}
1943
1944struct usb_page_cache *
1945usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1946{
1947	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1948
1949	return (&xfer->frbuffers[frindex]);
1950}
1951
1952void *
1953usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
1954{
1955	struct usb_page_search page_info;
1956
1957	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1958
1959	usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
1960	return (page_info.buffer);
1961}
1962
1963/*------------------------------------------------------------------------*
1964 *	usbd_xfer_get_fps_shift
1965 *
1966 * The following function is only useful for isochronous transfers. It
1967 * returns how many times the frame execution rate has been shifted
1968 * down.
1969 *
1970 * Return value:
1971 * Success: 0..3
1972 * Failure: 0
1973 *------------------------------------------------------------------------*/
1974uint8_t
1975usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1976{
1977	return (xfer->fps_shift);
1978}
1979
1980usb_frlength_t
1981usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1982{
1983	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1984
1985	return (xfer->frlengths[frindex]);
1986}
1987
1988/*------------------------------------------------------------------------*
1989 *	usbd_xfer_set_frame_data
1990 *
1991 * This function sets the pointer of the buffer that should
1992 * loaded directly into DMA for the given USB frame. Passing "ptr"
1993 * equal to NULL while the corresponding "frlength" is greater
1994 * than zero gives undefined results!
1995 *------------------------------------------------------------------------*/
1996void
1997usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1998    void *ptr, usb_frlength_t len)
1999{
2000	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2001
2002	/* set virtual address to load and length */
2003	xfer->frbuffers[frindex].buffer = ptr;
2004	usbd_xfer_set_frame_len(xfer, frindex, len);
2005}
2006
2007void
2008usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2009    void **ptr, int *len)
2010{
2011	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2012
2013	if (ptr != NULL)
2014		*ptr = xfer->frbuffers[frindex].buffer;
2015	if (len != NULL)
2016		*len = xfer->frlengths[frindex];
2017}
2018
2019/*------------------------------------------------------------------------*
2020 *	usbd_xfer_old_frame_length
2021 *
2022 * This function returns the framelength of the given frame at the
2023 * time the transfer was submitted. This function can be used to
2024 * compute the starting data pointer of the next isochronous frame
2025 * when an isochronous transfer has completed.
2026 *------------------------------------------------------------------------*/
2027usb_frlength_t
2028usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2029{
2030	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2031
2032	return (xfer->frlengths[frindex + xfer->max_frame_count]);
2033}
2034
2035void
2036usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2037    int *nframes)
2038{
2039	if (actlen != NULL)
2040		*actlen = xfer->actlen;
2041	if (sumlen != NULL)
2042		*sumlen = xfer->sumlen;
2043	if (aframes != NULL)
2044		*aframes = xfer->aframes;
2045	if (nframes != NULL)
2046		*nframes = xfer->nframes;
2047}
2048
2049/*------------------------------------------------------------------------*
2050 *	usbd_xfer_set_frame_offset
2051 *
2052 * This function sets the frame data buffer offset relative to the beginning
2053 * of the USB DMA buffer allocated for this USB transfer.
2054 *------------------------------------------------------------------------*/
2055void
2056usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2057    usb_frcount_t frindex)
2058{
2059	KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2060	    "when the USB buffer is external\n"));
2061	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2062
2063	/* set virtual address to load */
2064	xfer->frbuffers[frindex].buffer =
2065	    USB_ADD_BYTES(xfer->local_buffer, offset);
2066}
2067
2068void
2069usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2070{
2071	xfer->interval = i;
2072}
2073
2074void
2075usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2076{
2077	xfer->timeout = t;
2078}
2079
2080void
2081usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2082{
2083	xfer->nframes = n;
2084}
2085
2086usb_frcount_t
2087usbd_xfer_max_frames(struct usb_xfer *xfer)
2088{
2089	return (xfer->max_frame_count);
2090}
2091
2092usb_frlength_t
2093usbd_xfer_max_len(struct usb_xfer *xfer)
2094{
2095	return (xfer->max_data_length);
2096}
2097
2098usb_frlength_t
2099usbd_xfer_max_framelen(struct usb_xfer *xfer)
2100{
2101	return (xfer->max_frame_size);
2102}
2103
2104void
2105usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2106    usb_frlength_t len)
2107{
2108	KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2109
2110	xfer->frlengths[frindex] = len;
2111}
2112
2113/*------------------------------------------------------------------------*
2114 *	usb_callback_proc - factored out code
2115 *
2116 * This function performs USB callbacks.
2117 *------------------------------------------------------------------------*/
2118static void
2119usb_callback_proc(struct usb_proc_msg *_pm)
2120{
2121	struct usb_done_msg *pm = (void *)_pm;
2122	struct usb_xfer_root *info = pm->xroot;
2123
2124	/* Change locking order */
2125	USB_BUS_UNLOCK(info->bus);
2126
2127	/*
2128	 * We exploit the fact that the mutex is the same for all
2129	 * callbacks that will be called from this thread:
2130	 */
2131	mtx_lock(info->xfer_mtx);
2132	USB_BUS_LOCK(info->bus);
2133
2134	/* Continue where we lost track */
2135	usb_command_wrapper(&info->done_q,
2136	    info->done_q.curr);
2137
2138	mtx_unlock(info->xfer_mtx);
2139}
2140
2141/*------------------------------------------------------------------------*
2142 *	usbd_callback_ss_done_defer
2143 *
2144 * This function will defer the start, stop and done callback to the
2145 * correct thread.
2146 *------------------------------------------------------------------------*/
2147static void
2148usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2149{
2150	struct usb_xfer_root *info = xfer->xroot;
2151	struct usb_xfer_queue *pq = &info->done_q;
2152
2153	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2154
2155	if (pq->curr != xfer) {
2156		usbd_transfer_enqueue(pq, xfer);
2157	}
2158	if (!pq->recurse_1) {
2159
2160		/*
2161	         * We have to postpone the callback due to the fact we
2162	         * will have a Lock Order Reversal, LOR, if we try to
2163	         * proceed !
2164	         */
2165		if (usb_proc_msignal(info->done_p,
2166		    &info->done_m[0], &info->done_m[1])) {
2167			/* ignore */
2168		}
2169	} else {
2170		/* clear second recurse flag */
2171		pq->recurse_2 = 0;
2172	}
2173	return;
2174
2175}
2176
2177/*------------------------------------------------------------------------*
2178 *	usbd_callback_wrapper
2179 *
2180 * This is a wrapper for USB callbacks. This wrapper does some
2181 * auto-magic things like figuring out if we can call the callback
2182 * directly from the current context or if we need to wakeup the
2183 * interrupt process.
2184 *------------------------------------------------------------------------*/
2185static void
2186usbd_callback_wrapper(struct usb_xfer_queue *pq)
2187{
2188	struct usb_xfer *xfer = pq->curr;
2189	struct usb_xfer_root *info = xfer->xroot;
2190
2191	USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2192	if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2193		/*
2194	       	 * Cases that end up here:
2195		 *
2196		 * 5) HW interrupt done callback or other source.
2197		 */
2198		DPRINTFN(3, "case 5\n");
2199
2200		/*
2201	         * We have to postpone the callback due to the fact we
2202	         * will have a Lock Order Reversal, LOR, if we try to
2203	         * proceed !
2204	         */
2205		if (usb_proc_msignal(info->done_p,
2206		    &info->done_m[0], &info->done_m[1])) {
2207			/* ignore */
2208		}
2209		return;
2210	}
2211	/*
2212	 * Cases that end up here:
2213	 *
2214	 * 1) We are starting a transfer
2215	 * 2) We are prematurely calling back a transfer
2216	 * 3) We are stopping a transfer
2217	 * 4) We are doing an ordinary callback
2218	 */
2219	DPRINTFN(3, "case 1-4\n");
2220	/* get next USB transfer in the queue */
2221	info->done_q.curr = NULL;
2222
2223	/* set flag in case of drain */
2224	xfer->flags_int.doing_callback = 1;
2225
2226	USB_BUS_UNLOCK(info->bus);
2227	USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2228
2229	/* set correct USB state for callback */
2230	if (!xfer->flags_int.transferring) {
2231		xfer->usb_state = USB_ST_SETUP;
2232		if (!xfer->flags_int.started) {
2233			/* we got stopped before we even got started */
2234			USB_BUS_LOCK(info->bus);
2235			goto done;
2236		}
2237	} else {
2238
2239		if (usbd_callback_wrapper_sub(xfer)) {
2240			/* the callback has been deferred */
2241			USB_BUS_LOCK(info->bus);
2242			goto done;
2243		}
2244#if USB_HAVE_POWERD
2245		/* decrement power reference */
2246		usbd_transfer_power_ref(xfer, -1);
2247#endif
2248		xfer->flags_int.transferring = 0;
2249
2250		if (xfer->error) {
2251			xfer->usb_state = USB_ST_ERROR;
2252		} else {
2253			/* set transferred state */
2254			xfer->usb_state = USB_ST_TRANSFERRED;
2255#if USB_HAVE_BUSDMA
2256			/* sync DMA memory, if any */
2257			if (xfer->flags_int.bdma_enable &&
2258			    (!xfer->flags_int.bdma_no_post_sync)) {
2259				usb_bdma_post_sync(xfer);
2260			}
2261#endif
2262		}
2263	}
2264
2265#if USB_HAVE_PF
2266	if (xfer->usb_state != USB_ST_SETUP)
2267		usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2268#endif
2269	/* call processing routine */
2270	(xfer->callback) (xfer, xfer->error);
2271
2272	/* pickup the USB mutex again */
2273	USB_BUS_LOCK(info->bus);
2274
2275	/*
2276	 * Check if we got started after that we got cancelled, but
2277	 * before we managed to do the callback.
2278	 */
2279	if ((!xfer->flags_int.open) &&
2280	    (xfer->flags_int.started) &&
2281	    (xfer->usb_state == USB_ST_ERROR)) {
2282		/* clear flag in case of drain */
2283		xfer->flags_int.doing_callback = 0;
2284		/* try to loop, but not recursivly */
2285		usb_command_wrapper(&info->done_q, xfer);
2286		return;
2287	}
2288
2289done:
2290	/* clear flag in case of drain */
2291	xfer->flags_int.doing_callback = 0;
2292
2293	/*
2294	 * Check if we are draining.
2295	 */
2296	if (xfer->flags_int.draining &&
2297	    (!xfer->flags_int.transferring)) {
2298		/* "usbd_transfer_drain()" is waiting for end of transfer */
2299		xfer->flags_int.draining = 0;
2300		cv_broadcast(&info->cv_drain);
2301	}
2302
2303	/* do the next callback, if any */
2304	usb_command_wrapper(&info->done_q,
2305	    info->done_q.curr);
2306}
2307
2308/*------------------------------------------------------------------------*
2309 *	usb_dma_delay_done_cb
2310 *
2311 * This function is called when the DMA delay has been exectuded, and
2312 * will make sure that the callback is called to complete the USB
2313 * transfer. This code path is ususally only used when there is an USB
2314 * error like USB_ERR_CANCELLED.
2315 *------------------------------------------------------------------------*/
2316void
2317usb_dma_delay_done_cb(struct usb_xfer *xfer)
2318{
2319	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2320
2321	DPRINTFN(3, "Completed %p\n", xfer);
2322
2323	/* queue callback for execution, again */
2324	usbd_transfer_done(xfer, 0);
2325}
2326
2327/*------------------------------------------------------------------------*
2328 *	usbd_transfer_dequeue
2329 *
2330 *  - This function is used to remove an USB transfer from a USB
2331 *  transfer queue.
2332 *
2333 *  - This function can be called multiple times in a row.
2334 *------------------------------------------------------------------------*/
2335void
2336usbd_transfer_dequeue(struct usb_xfer *xfer)
2337{
2338	struct usb_xfer_queue *pq;
2339
2340	pq = xfer->wait_queue;
2341	if (pq) {
2342		TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2343		xfer->wait_queue = NULL;
2344	}
2345}
2346
2347/*------------------------------------------------------------------------*
2348 *	usbd_transfer_enqueue
2349 *
2350 *  - This function is used to insert an USB transfer into a USB *
2351 *  transfer queue.
2352 *
2353 *  - This function can be called multiple times in a row.
2354 *------------------------------------------------------------------------*/
2355void
2356usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2357{
2358	/*
2359	 * Insert the USB transfer into the queue, if it is not
2360	 * already on a USB transfer queue:
2361	 */
2362	if (xfer->wait_queue == NULL) {
2363		xfer->wait_queue = pq;
2364		TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2365	}
2366}
2367
2368/*------------------------------------------------------------------------*
2369 *	usbd_transfer_done
2370 *
2371 *  - This function is used to remove an USB transfer from the busdma,
2372 *  pipe or interrupt queue.
2373 *
2374 *  - This function is used to queue the USB transfer on the done
2375 *  queue.
2376 *
2377 *  - This function is used to stop any USB transfer timeouts.
2378 *------------------------------------------------------------------------*/
2379void
2380usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2381{
2382	struct usb_xfer_root *info = xfer->xroot;
2383
2384	USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2385
2386	DPRINTF("err=%s\n", usbd_errstr(error));
2387
2388	/*
2389	 * If we are not transferring then just return.
2390	 * This can happen during transfer cancel.
2391	 */
2392	if (!xfer->flags_int.transferring) {
2393		DPRINTF("not transferring\n");
2394		/* end of control transfer, if any */
2395		xfer->flags_int.control_act = 0;
2396		return;
2397	}
2398	/* only set transfer error, if not already set */
2399	if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2400		xfer->error = error;
2401
2402	/* stop any callouts */
2403	usb_callout_stop(&xfer->timeout_handle);
2404
2405	/*
2406	 * If we are waiting on a queue, just remove the USB transfer
2407	 * from the queue, if any. We should have the required locks
2408	 * locked to do the remove when this function is called.
2409	 */
2410	usbd_transfer_dequeue(xfer);
2411
2412#if USB_HAVE_BUSDMA
2413	if (mtx_owned(info->xfer_mtx)) {
2414		struct usb_xfer_queue *pq;
2415
2416		/*
2417		 * If the private USB lock is not locked, then we assume
2418		 * that the BUS-DMA load stage has been passed:
2419		 */
2420		pq = &info->dma_q;
2421
2422		if (pq->curr == xfer) {
2423			/* start the next BUS-DMA load, if any */
2424			usb_command_wrapper(pq, NULL);
2425		}
2426	}
2427#endif
2428	/* keep some statistics */
2429	if (xfer->error) {
2430		info->bus->stats_err.uds_requests
2431		    [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2432	} else {
2433		info->bus->stats_ok.uds_requests
2434		    [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2435	}
2436
2437	/* call the USB transfer callback */
2438	usbd_callback_ss_done_defer(xfer);
2439}
2440
2441/*------------------------------------------------------------------------*
2442 *	usbd_transfer_start_cb
2443 *
2444 * This function is called to start the USB transfer when
2445 * "xfer->interval" is greater than zero, and and the endpoint type is
2446 * BULK or CONTROL.
2447 *------------------------------------------------------------------------*/
2448static void
2449usbd_transfer_start_cb(void *arg)
2450{
2451	struct usb_xfer *xfer = arg;
2452	struct usb_endpoint *ep = xfer->endpoint;
2453
2454	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2455
2456	DPRINTF("start\n");
2457
2458#if USB_HAVE_PF
2459	usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2460#endif
2461
2462	/* the transfer can now be cancelled */
2463	xfer->flags_int.can_cancel_immed = 1;
2464
2465	/* start USB transfer, if no error */
2466	if (xfer->error == 0)
2467		(ep->methods->start) (xfer);
2468
2469	/* check for transfer error */
2470	if (xfer->error) {
2471		/* some error has happened */
2472		usbd_transfer_done(xfer, 0);
2473	}
2474}
2475
2476/*------------------------------------------------------------------------*
2477 *	usbd_xfer_set_stall
2478 *
2479 * This function is used to set the stall flag outside the
2480 * callback. This function is NULL safe.
2481 *------------------------------------------------------------------------*/
2482void
2483usbd_xfer_set_stall(struct usb_xfer *xfer)
2484{
2485	if (xfer == NULL) {
2486		/* tearing down */
2487		return;
2488	}
2489	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2490
2491	/* avoid any races by locking the USB mutex */
2492	USB_BUS_LOCK(xfer->xroot->bus);
2493	xfer->flags.stall_pipe = 1;
2494	USB_BUS_UNLOCK(xfer->xroot->bus);
2495}
2496
2497int
2498usbd_xfer_is_stalled(struct usb_xfer *xfer)
2499{
2500	return (xfer->endpoint->is_stalled);
2501}
2502
2503/*------------------------------------------------------------------------*
2504 *	usbd_transfer_clear_stall
2505 *
2506 * This function is used to clear the stall flag outside the
2507 * callback. This function is NULL safe.
2508 *------------------------------------------------------------------------*/
2509void
2510usbd_transfer_clear_stall(struct usb_xfer *xfer)
2511{
2512	if (xfer == NULL) {
2513		/* tearing down */
2514		return;
2515	}
2516	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2517
2518	/* avoid any races by locking the USB mutex */
2519	USB_BUS_LOCK(xfer->xroot->bus);
2520
2521	xfer->flags.stall_pipe = 0;
2522
2523	USB_BUS_UNLOCK(xfer->xroot->bus);
2524}
2525
2526/*------------------------------------------------------------------------*
2527 *	usbd_pipe_start
2528 *
2529 * This function is used to add an USB transfer to the pipe transfer list.
2530 *------------------------------------------------------------------------*/
2531void
2532usbd_pipe_start(struct usb_xfer_queue *pq)
2533{
2534	struct usb_endpoint *ep;
2535	struct usb_xfer *xfer;
2536	uint8_t type;
2537
2538	xfer = pq->curr;
2539	ep = xfer->endpoint;
2540
2541	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2542
2543	/*
2544	 * If the endpoint is already stalled we do nothing !
2545	 */
2546	if (ep->is_stalled) {
2547		return;
2548	}
2549	/*
2550	 * Check if we are supposed to stall the endpoint:
2551	 */
2552	if (xfer->flags.stall_pipe) {
2553		struct usb_device *udev;
2554		struct usb_xfer_root *info;
2555
2556		/* clear stall command */
2557		xfer->flags.stall_pipe = 0;
2558
2559		/* get pointer to USB device */
2560		info = xfer->xroot;
2561		udev = info->udev;
2562
2563		/*
2564		 * Only stall BULK and INTERRUPT endpoints.
2565		 */
2566		type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2567		if ((type == UE_BULK) ||
2568		    (type == UE_INTERRUPT)) {
2569			uint8_t did_stall;
2570
2571			did_stall = 1;
2572
2573			if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2574				(udev->bus->methods->set_stall) (
2575				    udev, NULL, ep, &did_stall);
2576			} else if (udev->ctrl_xfer[1]) {
2577				info = udev->ctrl_xfer[1]->xroot;
2578				usb_proc_msignal(
2579				    &info->bus->non_giant_callback_proc,
2580				    &udev->cs_msg[0], &udev->cs_msg[1]);
2581			} else {
2582				/* should not happen */
2583				DPRINTFN(0, "No stall handler\n");
2584			}
2585			/*
2586			 * Check if we should stall. Some USB hardware
2587			 * handles set- and clear-stall in hardware.
2588			 */
2589			if (did_stall) {
2590				/*
2591				 * The transfer will be continued when
2592				 * the clear-stall control endpoint
2593				 * message is received.
2594				 */
2595				ep->is_stalled = 1;
2596				return;
2597			}
2598		} else if (type == UE_ISOCHRONOUS) {
2599
2600			/*
2601			 * Make sure any FIFO overflow or other FIFO
2602			 * error conditions go away by resetting the
2603			 * endpoint FIFO through the clear stall
2604			 * method.
2605			 */
2606			if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2607				(udev->bus->methods->clear_stall) (udev, ep);
2608			}
2609		}
2610	}
2611	/* Set or clear stall complete - special case */
2612	if (xfer->nframes == 0) {
2613		/* we are complete */
2614		xfer->aframes = 0;
2615		usbd_transfer_done(xfer, 0);
2616		return;
2617	}
2618	/*
2619	 * Handled cases:
2620	 *
2621	 * 1) Start the first transfer queued.
2622	 *
2623	 * 2) Re-start the current USB transfer.
2624	 */
2625	/*
2626	 * Check if there should be any
2627	 * pre transfer start delay:
2628	 */
2629	if (xfer->interval > 0) {
2630		type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2631		if ((type == UE_BULK) ||
2632		    (type == UE_CONTROL)) {
2633			usbd_transfer_timeout_ms(xfer,
2634			    &usbd_transfer_start_cb,
2635			    xfer->interval);
2636			return;
2637		}
2638	}
2639	DPRINTF("start\n");
2640
2641#if USB_HAVE_PF
2642	usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2643#endif
2644	/* the transfer can now be cancelled */
2645	xfer->flags_int.can_cancel_immed = 1;
2646
2647	/* start USB transfer, if no error */
2648	if (xfer->error == 0)
2649		(ep->methods->start) (xfer);
2650
2651	/* check for transfer error */
2652	if (xfer->error) {
2653		/* some error has happened */
2654		usbd_transfer_done(xfer, 0);
2655	}
2656}
2657
2658/*------------------------------------------------------------------------*
2659 *	usbd_transfer_timeout_ms
2660 *
2661 * This function is used to setup a timeout on the given USB
2662 * transfer. If the timeout has been deferred the callback given by
2663 * "cb" will get called after "ms" milliseconds.
2664 *------------------------------------------------------------------------*/
2665void
2666usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2667    void (*cb) (void *arg), usb_timeout_t ms)
2668{
2669	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2670
2671	/* defer delay */
2672	usb_callout_reset(&xfer->timeout_handle,
2673	    USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2674}
2675
2676/*------------------------------------------------------------------------*
2677 *	usbd_callback_wrapper_sub
2678 *
2679 *  - This function will update variables in an USB transfer after
2680 *  that the USB transfer is complete.
2681 *
2682 *  - This function is used to start the next USB transfer on the
2683 *  ep transfer queue, if any.
2684 *
2685 * NOTE: In some special cases the USB transfer will not be removed from
2686 * the pipe queue, but remain first. To enforce USB transfer removal call
2687 * this function passing the error code "USB_ERR_CANCELLED".
2688 *
2689 * Return values:
2690 * 0: Success.
2691 * Else: The callback has been deferred.
2692 *------------------------------------------------------------------------*/
2693static uint8_t
2694usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2695{
2696	struct usb_endpoint *ep;
2697	struct usb_bus *bus;
2698	usb_frcount_t x;
2699
2700	bus = xfer->xroot->bus;
2701
2702	if ((!xfer->flags_int.open) &&
2703	    (!xfer->flags_int.did_close)) {
2704		DPRINTF("close\n");
2705		USB_BUS_LOCK(bus);
2706		(xfer->endpoint->methods->close) (xfer);
2707		USB_BUS_UNLOCK(bus);
2708		/* only close once */
2709		xfer->flags_int.did_close = 1;
2710		return (1);		/* wait for new callback */
2711	}
2712	/*
2713	 * If we have a non-hardware induced error we
2714	 * need to do the DMA delay!
2715	 */
2716	if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2717	    (xfer->error == USB_ERR_CANCELLED ||
2718	    xfer->error == USB_ERR_TIMEOUT ||
2719	    bus->methods->start_dma_delay != NULL)) {
2720
2721		usb_timeout_t temp;
2722
2723		/* only delay once */
2724		xfer->flags_int.did_dma_delay = 1;
2725
2726		/* we can not cancel this delay */
2727		xfer->flags_int.can_cancel_immed = 0;
2728
2729		temp = usbd_get_dma_delay(xfer->xroot->udev);
2730
2731		DPRINTFN(3, "DMA delay, %u ms, "
2732		    "on %p\n", temp, xfer);
2733
2734		if (temp != 0) {
2735			USB_BUS_LOCK(bus);
2736			/*
2737			 * Some hardware solutions have dedicated
2738			 * events when it is safe to free DMA'ed
2739			 * memory. For the other hardware platforms we
2740			 * use a static delay.
2741			 */
2742			if (bus->methods->start_dma_delay != NULL) {
2743				(bus->methods->start_dma_delay) (xfer);
2744			} else {
2745				usbd_transfer_timeout_ms(xfer,
2746				    (void (*)(void *))&usb_dma_delay_done_cb,
2747				    temp);
2748			}
2749			USB_BUS_UNLOCK(bus);
2750			return (1);	/* wait for new callback */
2751		}
2752	}
2753	/* check actual number of frames */
2754	if (xfer->aframes > xfer->nframes) {
2755		if (xfer->error == 0) {
2756			panic("%s: actual number of frames, %d, is "
2757			    "greater than initial number of frames, %d\n",
2758			    __FUNCTION__, xfer->aframes, xfer->nframes);
2759		} else {
2760			/* just set some valid value */
2761			xfer->aframes = xfer->nframes;
2762		}
2763	}
2764	/* compute actual length */
2765	xfer->actlen = 0;
2766
2767	for (x = 0; x != xfer->aframes; x++) {
2768		xfer->actlen += xfer->frlengths[x];
2769	}
2770
2771	/*
2772	 * Frames that were not transferred get zero actual length in
2773	 * case the USB device driver does not check the actual number
2774	 * of frames transferred, "xfer->aframes":
2775	 */
2776	for (; x < xfer->nframes; x++) {
2777		usbd_xfer_set_frame_len(xfer, x, 0);
2778	}
2779
2780	/* check actual length */
2781	if (xfer->actlen > xfer->sumlen) {
2782		if (xfer->error == 0) {
2783			panic("%s: actual length, %d, is greater than "
2784			    "initial length, %d\n",
2785			    __FUNCTION__, xfer->actlen, xfer->sumlen);
2786		} else {
2787			/* just set some valid value */
2788			xfer->actlen = xfer->sumlen;
2789		}
2790	}
2791	DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2792	    xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2793	    xfer->aframes, xfer->nframes);
2794
2795	if (xfer->error) {
2796		/* end of control transfer, if any */
2797		xfer->flags_int.control_act = 0;
2798
2799#if USB_HAVE_TT_SUPPORT
2800		switch (xfer->error) {
2801		case USB_ERR_NORMAL_COMPLETION:
2802		case USB_ERR_SHORT_XFER:
2803		case USB_ERR_STALLED:
2804		case USB_ERR_CANCELLED:
2805			/* nothing to do */
2806			break;
2807		default:
2808			/* try to reset the TT, if any */
2809			USB_BUS_LOCK(bus);
2810			uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2811			USB_BUS_UNLOCK(bus);
2812			break;
2813		}
2814#endif
2815		/* check if we should block the execution queue */
2816		if ((xfer->error != USB_ERR_CANCELLED) &&
2817		    (xfer->flags.pipe_bof)) {
2818			DPRINTFN(2, "xfer=%p: Block On Failure "
2819			    "on endpoint=%p\n", xfer, xfer->endpoint);
2820			goto done;
2821		}
2822	} else {
2823		/* check for short transfers */
2824		if (xfer->actlen < xfer->sumlen) {
2825
2826			/* end of control transfer, if any */
2827			xfer->flags_int.control_act = 0;
2828
2829			if (!xfer->flags_int.short_xfer_ok) {
2830				xfer->error = USB_ERR_SHORT_XFER;
2831				if (xfer->flags.pipe_bof) {
2832					DPRINTFN(2, "xfer=%p: Block On Failure on "
2833					    "Short Transfer on endpoint %p.\n",
2834					    xfer, xfer->endpoint);
2835					goto done;
2836				}
2837			}
2838		} else {
2839			/*
2840			 * Check if we are in the middle of a
2841			 * control transfer:
2842			 */
2843			if (xfer->flags_int.control_act) {
2844				DPRINTFN(5, "xfer=%p: Control transfer "
2845				    "active on endpoint=%p\n", xfer, xfer->endpoint);
2846				goto done;
2847			}
2848		}
2849	}
2850
2851	ep = xfer->endpoint;
2852
2853	/*
2854	 * If the current USB transfer is completing we need to start the
2855	 * next one:
2856	 */
2857	USB_BUS_LOCK(bus);
2858	if (ep->endpoint_q.curr == xfer) {
2859		usb_command_wrapper(&ep->endpoint_q, NULL);
2860
2861		if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2862			/* there is another USB transfer waiting */
2863		} else {
2864			/* this is the last USB transfer */
2865			/* clear isochronous sync flag */
2866			xfer->endpoint->is_synced = 0;
2867		}
2868	}
2869	USB_BUS_UNLOCK(bus);
2870done:
2871	return (0);
2872}
2873
2874/*------------------------------------------------------------------------*
2875 *	usb_command_wrapper
2876 *
2877 * This function is used to execute commands non-recursivly on an USB
2878 * transfer.
2879 *------------------------------------------------------------------------*/
2880void
2881usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2882{
2883	if (xfer) {
2884		/*
2885		 * If the transfer is not already processing,
2886		 * queue it!
2887		 */
2888		if (pq->curr != xfer) {
2889			usbd_transfer_enqueue(pq, xfer);
2890			if (pq->curr != NULL) {
2891				/* something is already processing */
2892				DPRINTFN(6, "busy %p\n", pq->curr);
2893				return;
2894			}
2895		}
2896	} else {
2897		/* Get next element in queue */
2898		pq->curr = NULL;
2899	}
2900
2901	if (!pq->recurse_1) {
2902
2903		do {
2904
2905			/* set both recurse flags */
2906			pq->recurse_1 = 1;
2907			pq->recurse_2 = 1;
2908
2909			if (pq->curr == NULL) {
2910				xfer = TAILQ_FIRST(&pq->head);
2911				if (xfer) {
2912					TAILQ_REMOVE(&pq->head, xfer,
2913					    wait_entry);
2914					xfer->wait_queue = NULL;
2915					pq->curr = xfer;
2916				} else {
2917					break;
2918				}
2919			}
2920			DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2921			(pq->command) (pq);
2922			DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2923
2924		} while (!pq->recurse_2);
2925
2926		/* clear first recurse flag */
2927		pq->recurse_1 = 0;
2928
2929	} else {
2930		/* clear second recurse flag */
2931		pq->recurse_2 = 0;
2932	}
2933}
2934
2935/*------------------------------------------------------------------------*
2936 *	usbd_ctrl_transfer_setup
2937 *
2938 * This function is used to setup the default USB control endpoint
2939 * transfer.
2940 *------------------------------------------------------------------------*/
2941void
2942usbd_ctrl_transfer_setup(struct usb_device *udev)
2943{
2944	struct usb_xfer *xfer;
2945	uint8_t no_resetup;
2946	uint8_t iface_index;
2947
2948	/* check for root HUB */
2949	if (udev->parent_hub == NULL)
2950		return;
2951repeat:
2952
2953	xfer = udev->ctrl_xfer[0];
2954	if (xfer) {
2955		USB_XFER_LOCK(xfer);
2956		no_resetup =
2957		    ((xfer->address == udev->address) &&
2958		    (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2959		    udev->ddesc.bMaxPacketSize));
2960		if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2961			if (no_resetup) {
2962				/*
2963				 * NOTE: checking "xfer->address" and
2964				 * starting the USB transfer must be
2965				 * atomic!
2966				 */
2967				usbd_transfer_start(xfer);
2968			}
2969		}
2970		USB_XFER_UNLOCK(xfer);
2971	} else {
2972		no_resetup = 0;
2973	}
2974
2975	if (no_resetup) {
2976		/*
2977	         * All parameters are exactly the same like before.
2978	         * Just return.
2979	         */
2980		return;
2981	}
2982	/*
2983	 * Update wMaxPacketSize for the default control endpoint:
2984	 */
2985	udev->ctrl_ep_desc.wMaxPacketSize[0] =
2986	    udev->ddesc.bMaxPacketSize;
2987
2988	/*
2989	 * Unsetup any existing USB transfer:
2990	 */
2991	usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2992
2993	/*
2994	 * Reset clear stall error counter.
2995	 */
2996	udev->clear_stall_errors = 0;
2997
2998	/*
2999	 * Try to setup a new USB transfer for the
3000	 * default control endpoint:
3001	 */
3002	iface_index = 0;
3003	if (usbd_transfer_setup(udev, &iface_index,
3004	    udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3005	    &udev->device_mtx)) {
3006		DPRINTFN(0, "could not setup default "
3007		    "USB transfer\n");
3008	} else {
3009		goto repeat;
3010	}
3011}
3012
3013/*------------------------------------------------------------------------*
3014 *	usbd_clear_data_toggle - factored out code
3015 *
3016 * NOTE: the intention of this function is not to reset the hardware
3017 * data toggle.
3018 *------------------------------------------------------------------------*/
3019void
3020usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3021{
3022	USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3023
3024	/* check that we have a valid case */
3025	if (udev->flags.usb_mode == USB_MODE_HOST &&
3026	    udev->parent_hub != NULL &&
3027	    udev->bus->methods->clear_stall != NULL &&
3028	    ep->methods != NULL) {
3029		(udev->bus->methods->clear_stall) (udev, ep);
3030	}
3031}
3032
3033/*------------------------------------------------------------------------*
3034 *	usbd_clear_data_toggle - factored out code
3035 *
3036 * NOTE: the intention of this function is not to reset the hardware
3037 * data toggle on the USB device side.
3038 *------------------------------------------------------------------------*/
3039void
3040usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3041{
3042	DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3043
3044	USB_BUS_LOCK(udev->bus);
3045	ep->toggle_next = 0;
3046	/* some hardware needs a callback to clear the data toggle */
3047	usbd_clear_stall_locked(udev, ep);
3048	USB_BUS_UNLOCK(udev->bus);
3049}
3050
3051/*------------------------------------------------------------------------*
3052 *	usbd_clear_stall_callback - factored out clear stall callback
3053 *
3054 * Input parameters:
3055 *  xfer1: Clear Stall Control Transfer
3056 *  xfer2: Stalled USB Transfer
3057 *
3058 * This function is NULL safe.
3059 *
3060 * Return values:
3061 *   0: In progress
3062 *   Else: Finished
3063 *
3064 * Clear stall config example:
3065 *
3066 * static const struct usb_config my_clearstall =  {
3067 *	.type = UE_CONTROL,
3068 *	.endpoint = 0,
3069 *	.direction = UE_DIR_ANY,
3070 *	.interval = 50, //50 milliseconds
3071 *	.bufsize = sizeof(struct usb_device_request),
3072 *	.timeout = 1000, //1.000 seconds
3073 *	.callback = &my_clear_stall_callback, // **
3074 *	.usb_mode = USB_MODE_HOST,
3075 * };
3076 *
3077 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3078 * passing the correct parameters.
3079 *------------------------------------------------------------------------*/
3080uint8_t
3081usbd_clear_stall_callback(struct usb_xfer *xfer1,
3082    struct usb_xfer *xfer2)
3083{
3084	struct usb_device_request req;
3085
3086	if (xfer2 == NULL) {
3087		/* looks like we are tearing down */
3088		DPRINTF("NULL input parameter\n");
3089		return (0);
3090	}
3091	USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3092	USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3093
3094	switch (USB_GET_STATE(xfer1)) {
3095	case USB_ST_SETUP:
3096
3097		/*
3098		 * pre-clear the data toggle to DATA0 ("umass.c" and
3099		 * "ata-usb.c" depends on this)
3100		 */
3101
3102		usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3103
3104		/* setup a clear-stall packet */
3105
3106		req.bmRequestType = UT_WRITE_ENDPOINT;
3107		req.bRequest = UR_CLEAR_FEATURE;
3108		USETW(req.wValue, UF_ENDPOINT_HALT);
3109		req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3110		req.wIndex[1] = 0;
3111		USETW(req.wLength, 0);
3112
3113		/*
3114		 * "usbd_transfer_setup_sub()" will ensure that
3115		 * we have sufficient room in the buffer for
3116		 * the request structure!
3117		 */
3118
3119		/* copy in the transfer */
3120
3121		usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3122
3123		/* set length */
3124		xfer1->frlengths[0] = sizeof(req);
3125		xfer1->nframes = 1;
3126
3127		usbd_transfer_submit(xfer1);
3128		return (0);
3129
3130	case USB_ST_TRANSFERRED:
3131		break;
3132
3133	default:			/* Error */
3134		if (xfer1->error == USB_ERR_CANCELLED) {
3135			return (0);
3136		}
3137		break;
3138	}
3139	return (1);			/* Clear Stall Finished */
3140}
3141
3142/*------------------------------------------------------------------------*
3143 *	usbd_transfer_poll
3144 *
3145 * The following function gets called from the USB keyboard driver and
3146 * UMASS when the system has paniced.
3147 *
3148 * NOTE: It is currently not possible to resume normal operation on
3149 * the USB controller which has been polled, due to clearing of the
3150 * "up_dsleep" and "up_msleep" flags.
3151 *------------------------------------------------------------------------*/
3152void
3153usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3154{
3155	struct usb_xfer *xfer;
3156	struct usb_xfer_root *xroot;
3157	struct usb_device *udev;
3158	struct usb_proc_msg *pm;
3159	uint16_t n;
3160	uint16_t drop_bus;
3161	uint16_t drop_xfer;
3162
3163	for (n = 0; n != max; n++) {
3164		/* Extra checks to avoid panic */
3165		xfer = ppxfer[n];
3166		if (xfer == NULL)
3167			continue;	/* no USB transfer */
3168		xroot = xfer->xroot;
3169		if (xroot == NULL)
3170			continue;	/* no USB root */
3171		udev = xroot->udev;
3172		if (udev == NULL)
3173			continue;	/* no USB device */
3174		if (udev->bus == NULL)
3175			continue;	/* no BUS structure */
3176		if (udev->bus->methods == NULL)
3177			continue;	/* no BUS methods */
3178		if (udev->bus->methods->xfer_poll == NULL)
3179			continue;	/* no poll method */
3180
3181		/* make sure that the BUS mutex is not locked */
3182		drop_bus = 0;
3183		while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3184			mtx_unlock(&xroot->udev->bus->bus_mtx);
3185			drop_bus++;
3186		}
3187
3188		/* make sure that the transfer mutex is not locked */
3189		drop_xfer = 0;
3190		while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3191			mtx_unlock(xroot->xfer_mtx);
3192			drop_xfer++;
3193		}
3194
3195		/* Make sure cv_signal() and cv_broadcast() is not called */
3196		udev->bus->control_xfer_proc.up_msleep = 0;
3197		udev->bus->explore_proc.up_msleep = 0;
3198		udev->bus->giant_callback_proc.up_msleep = 0;
3199		udev->bus->non_giant_callback_proc.up_msleep = 0;
3200
3201		/* poll USB hardware */
3202		(udev->bus->methods->xfer_poll) (udev->bus);
3203
3204		USB_BUS_LOCK(xroot->bus);
3205
3206		/* check for clear stall */
3207		if (udev->ctrl_xfer[1] != NULL) {
3208
3209			/* poll clear stall start */
3210			pm = &udev->cs_msg[0].hdr;
3211			(pm->pm_callback) (pm);
3212			/* poll clear stall done thread */
3213			pm = &udev->ctrl_xfer[1]->
3214			    xroot->done_m[0].hdr;
3215			(pm->pm_callback) (pm);
3216		}
3217
3218		/* poll done thread */
3219		pm = &xroot->done_m[0].hdr;
3220		(pm->pm_callback) (pm);
3221
3222		USB_BUS_UNLOCK(xroot->bus);
3223
3224		/* restore transfer mutex */
3225		while (drop_xfer--)
3226			mtx_lock(xroot->xfer_mtx);
3227
3228		/* restore BUS mutex */
3229		while (drop_bus--)
3230			mtx_lock(&xroot->udev->bus->bus_mtx);
3231	}
3232}
3233
3234static void
3235usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3236    uint8_t type, enum usb_dev_speed speed)
3237{
3238	static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3239		[USB_SPEED_LOW] = 8,
3240		[USB_SPEED_FULL] = 64,
3241		[USB_SPEED_HIGH] = 1024,
3242		[USB_SPEED_VARIABLE] = 1024,
3243		[USB_SPEED_SUPER] = 1024,
3244	};
3245
3246	static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3247		[USB_SPEED_LOW] = 0,	/* invalid */
3248		[USB_SPEED_FULL] = 1023,
3249		[USB_SPEED_HIGH] = 1024,
3250		[USB_SPEED_VARIABLE] = 3584,
3251		[USB_SPEED_SUPER] = 1024,
3252	};
3253
3254	static const uint16_t control_min[USB_SPEED_MAX] = {
3255		[USB_SPEED_LOW] = 8,
3256		[USB_SPEED_FULL] = 8,
3257		[USB_SPEED_HIGH] = 64,
3258		[USB_SPEED_VARIABLE] = 512,
3259		[USB_SPEED_SUPER] = 512,
3260	};
3261
3262	static const uint16_t bulk_min[USB_SPEED_MAX] = {
3263		[USB_SPEED_LOW] = 8,
3264		[USB_SPEED_FULL] = 8,
3265		[USB_SPEED_HIGH] = 512,
3266		[USB_SPEED_VARIABLE] = 512,
3267		[USB_SPEED_SUPER] = 1024,
3268	};
3269
3270	uint16_t temp;
3271
3272	memset(ptr, 0, sizeof(*ptr));
3273
3274	switch (type) {
3275	case UE_INTERRUPT:
3276		ptr->range.max = intr_range_max[speed];
3277		break;
3278	case UE_ISOCHRONOUS:
3279		ptr->range.max = isoc_range_max[speed];
3280		break;
3281	default:
3282		if (type == UE_BULK)
3283			temp = bulk_min[speed];
3284		else /* UE_CONTROL */
3285			temp = control_min[speed];
3286
3287		/* default is fixed */
3288		ptr->fixed[0] = temp;
3289		ptr->fixed[1] = temp;
3290		ptr->fixed[2] = temp;
3291		ptr->fixed[3] = temp;
3292
3293		if (speed == USB_SPEED_FULL) {
3294			/* multiple sizes */
3295			ptr->fixed[1] = 16;
3296			ptr->fixed[2] = 32;
3297			ptr->fixed[3] = 64;
3298		}
3299		if ((speed == USB_SPEED_VARIABLE) &&
3300		    (type == UE_BULK)) {
3301			/* multiple sizes */
3302			ptr->fixed[2] = 1024;
3303			ptr->fixed[3] = 1536;
3304		}
3305		break;
3306	}
3307}
3308
3309void	*
3310usbd_xfer_softc(struct usb_xfer *xfer)
3311{
3312	return (xfer->priv_sc);
3313}
3314
3315void *
3316usbd_xfer_get_priv(struct usb_xfer *xfer)
3317{
3318	return (xfer->priv_fifo);
3319}
3320
3321void
3322usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3323{
3324	xfer->priv_fifo = ptr;
3325}
3326
3327uint8_t
3328usbd_xfer_state(struct usb_xfer *xfer)
3329{
3330	return (xfer->usb_state);
3331}
3332
3333void
3334usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3335{
3336	switch (flag) {
3337		case USB_FORCE_SHORT_XFER:
3338			xfer->flags.force_short_xfer = 1;
3339			break;
3340		case USB_SHORT_XFER_OK:
3341			xfer->flags.short_xfer_ok = 1;
3342			break;
3343		case USB_MULTI_SHORT_OK:
3344			xfer->flags.short_frames_ok = 1;
3345			break;
3346		case USB_MANUAL_STATUS:
3347			xfer->flags.manual_status = 1;
3348			break;
3349	}
3350}
3351
3352void
3353usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3354{
3355	switch (flag) {
3356		case USB_FORCE_SHORT_XFER:
3357			xfer->flags.force_short_xfer = 0;
3358			break;
3359		case USB_SHORT_XFER_OK:
3360			xfer->flags.short_xfer_ok = 0;
3361			break;
3362		case USB_MULTI_SHORT_OK:
3363			xfer->flags.short_frames_ok = 0;
3364			break;
3365		case USB_MANUAL_STATUS:
3366			xfer->flags.manual_status = 0;
3367			break;
3368	}
3369}
3370
3371/*
3372 * The following function returns in milliseconds when the isochronous
3373 * transfer was completed by the hardware. The returned value wraps
3374 * around 65536 milliseconds.
3375 */
3376uint16_t
3377usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3378{
3379	return (xfer->isoc_time_complete);
3380}
3381
3382/*
3383 * The following function returns non-zero if the max packet size
3384 * field was clamped to a valid value. Else it returns zero.
3385 */
3386uint8_t
3387usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3388{
3389	return (xfer->flags_int.maxp_was_clamped);
3390}
3391