xref: /netbsd-src/sys/dev/usb/ehci.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: ehci.c,v 1.205 2013/02/01 12:53:47 tsutsui Exp $ */
2 
3 /*
4  * Copyright (c) 2004-2012 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (lennart@augustsson.net), Charles M. Hannum,
9  * Jeremy Morse (jeremy.morse@gmail.com), Jared D. McNeill
10  * (jmcneill@invisible.ca) and Matthew R. Green (mrg@eterna.com.au).
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * USB Enhanced Host Controller Driver, a.k.a. USB 2.0 controller.
36  *
37  * The EHCI 1.0 spec can be found at
38  * http://www.intel.com/technology/usb/spec.htm
39  * and the USB 2.0 spec at
40  * http://www.usb.org/developers/docs/
41  *
42  */
43 
44 /*
45  * TODO:
46  * 1) hold off explorations by companion controllers until ehci has started.
47  *
48  * 2) The hub driver needs to handle and schedule the transaction translator,
49  *    to assign place in frame where different devices get to go. See chapter
50  *    on hubs in USB 2.0 for details.
51  *
52  * 3) Command failures are not recovered correctly.
53  */
54 
55 #include <sys/cdefs.h>
56 __KERNEL_RCSID(0, "$NetBSD: ehci.c,v 1.205 2013/02/01 12:53:47 tsutsui Exp $");
57 
58 #include "ohci.h"
59 #include "uhci.h"
60 
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
64 #include <sys/kmem.h>
65 #include <sys/device.h>
66 #include <sys/select.h>
67 #include <sys/proc.h>
68 #include <sys/queue.h>
69 #include <sys/mutex.h>
70 #include <sys/bus.h>
71 #include <sys/cpu.h>
72 
73 #include <machine/endian.h>
74 
75 #include <dev/usb/usb.h>
76 #include <dev/usb/usbdi.h>
77 #include <dev/usb/usbdivar.h>
78 #include <dev/usb/usb_mem.h>
79 #include <dev/usb/usb_quirks.h>
80 
81 #include <dev/usb/ehcireg.h>
82 #include <dev/usb/ehcivar.h>
83 #include <dev/usb/usbroothub_subr.h>
84 
85 #ifdef EHCI_DEBUG
86 static void __printflike(1, 2)
87 ehciprintf(const char *fmt, ...)
88 {
89 	va_list ap;
90 
91 	va_start(ap, fmt);
92 	vprintf(fmt, ap);
93 	va_end(ap);
94 }
95 
96 #define DPRINTF(x)	do { if (ehcidebug) ehciprintf x; } while(0)
97 #define DPRINTFN(n,x)	do { if (ehcidebug>(n)) ehciprintf x; } while (0)
98 int ehcidebug = 0;
99 #else
100 #define DPRINTF(x)
101 #define DPRINTFN(n,x)
102 #endif
103 
104 struct ehci_pipe {
105 	struct usbd_pipe pipe;
106 	int nexttoggle;
107 
108 	ehci_soft_qh_t *sqh;
109 	union {
110 		ehci_soft_qtd_t *qtd;
111 		/* ehci_soft_itd_t *itd; */
112 	} tail;
113 	union {
114 		/* Control pipe */
115 		struct {
116 			usb_dma_t reqdma;
117 		} ctl;
118 		/* Interrupt pipe */
119 		struct {
120 			u_int length;
121 		} intr;
122 		/* Bulk pipe */
123 		struct {
124 			u_int length;
125 		} bulk;
126 		/* Iso pipe */
127 		struct {
128 			u_int next_frame;
129 			u_int cur_xfers;
130 		} isoc;
131 	} u;
132 };
133 
134 Static usbd_status	ehci_open(usbd_pipe_handle);
135 Static void		ehci_poll(struct usbd_bus *);
136 Static void		ehci_softintr(void *);
137 Static int		ehci_intr1(ehci_softc_t *);
138 Static void		ehci_waitintr(ehci_softc_t *, usbd_xfer_handle);
139 Static void		ehci_check_intr(ehci_softc_t *, struct ehci_xfer *);
140 Static void		ehci_check_qh_intr(ehci_softc_t *, struct ehci_xfer *);
141 Static void		ehci_check_itd_intr(ehci_softc_t *, struct ehci_xfer *);
142 Static void		ehci_idone(struct ehci_xfer *);
143 Static void		ehci_timeout(void *);
144 Static void		ehci_timeout_task(void *);
145 Static void		ehci_intrlist_timeout(void *);
146 Static void		ehci_doorbell(void *);
147 Static void		ehci_pcd(void *);
148 
149 Static usbd_status	ehci_allocm(struct usbd_bus *, usb_dma_t *, u_int32_t);
150 Static void		ehci_freem(struct usbd_bus *, usb_dma_t *);
151 
152 Static usbd_xfer_handle	ehci_allocx(struct usbd_bus *);
153 Static void		ehci_freex(struct usbd_bus *, usbd_xfer_handle);
154 Static void		ehci_get_lock(struct usbd_bus *, kmutex_t **);
155 
156 Static usbd_status	ehci_root_ctrl_transfer(usbd_xfer_handle);
157 Static usbd_status	ehci_root_ctrl_start(usbd_xfer_handle);
158 Static void		ehci_root_ctrl_abort(usbd_xfer_handle);
159 Static void		ehci_root_ctrl_close(usbd_pipe_handle);
160 Static void		ehci_root_ctrl_done(usbd_xfer_handle);
161 
162 Static usbd_status	ehci_root_intr_transfer(usbd_xfer_handle);
163 Static usbd_status	ehci_root_intr_start(usbd_xfer_handle);
164 Static void		ehci_root_intr_abort(usbd_xfer_handle);
165 Static void		ehci_root_intr_close(usbd_pipe_handle);
166 Static void		ehci_root_intr_done(usbd_xfer_handle);
167 
168 Static usbd_status	ehci_device_ctrl_transfer(usbd_xfer_handle);
169 Static usbd_status	ehci_device_ctrl_start(usbd_xfer_handle);
170 Static void		ehci_device_ctrl_abort(usbd_xfer_handle);
171 Static void		ehci_device_ctrl_close(usbd_pipe_handle);
172 Static void		ehci_device_ctrl_done(usbd_xfer_handle);
173 
174 Static usbd_status	ehci_device_bulk_transfer(usbd_xfer_handle);
175 Static usbd_status	ehci_device_bulk_start(usbd_xfer_handle);
176 Static void		ehci_device_bulk_abort(usbd_xfer_handle);
177 Static void		ehci_device_bulk_close(usbd_pipe_handle);
178 Static void		ehci_device_bulk_done(usbd_xfer_handle);
179 
180 Static usbd_status	ehci_device_intr_transfer(usbd_xfer_handle);
181 Static usbd_status	ehci_device_intr_start(usbd_xfer_handle);
182 Static void		ehci_device_intr_abort(usbd_xfer_handle);
183 Static void		ehci_device_intr_close(usbd_pipe_handle);
184 Static void		ehci_device_intr_done(usbd_xfer_handle);
185 
186 Static usbd_status	ehci_device_isoc_transfer(usbd_xfer_handle);
187 Static usbd_status	ehci_device_isoc_start(usbd_xfer_handle);
188 Static void		ehci_device_isoc_abort(usbd_xfer_handle);
189 Static void		ehci_device_isoc_close(usbd_pipe_handle);
190 Static void		ehci_device_isoc_done(usbd_xfer_handle);
191 
192 Static void		ehci_device_clear_toggle(usbd_pipe_handle pipe);
193 Static void		ehci_noop(usbd_pipe_handle pipe);
194 
195 Static void		ehci_disown(ehci_softc_t *, int, int);
196 
197 Static ehci_soft_qh_t  *ehci_alloc_sqh(ehci_softc_t *);
198 Static void		ehci_free_sqh(ehci_softc_t *, ehci_soft_qh_t *);
199 
200 Static ehci_soft_qtd_t  *ehci_alloc_sqtd(ehci_softc_t *);
201 Static void		ehci_free_sqtd(ehci_softc_t *, ehci_soft_qtd_t *);
202 Static usbd_status	ehci_alloc_sqtd_chain(struct ehci_pipe *,
203 			    ehci_softc_t *, int, int, usbd_xfer_handle,
204 			    ehci_soft_qtd_t **, ehci_soft_qtd_t **);
205 Static void		ehci_free_sqtd_chain(ehci_softc_t *, ehci_soft_qtd_t *,
206 					    ehci_soft_qtd_t *);
207 
208 Static ehci_soft_itd_t	*ehci_alloc_itd(ehci_softc_t *sc);
209 Static void		ehci_free_itd(ehci_softc_t *sc, ehci_soft_itd_t *itd);
210 Static void 		ehci_rem_free_itd_chain(ehci_softc_t *sc,
211 						struct ehci_xfer *exfer);
212 Static void 		ehci_abort_isoc_xfer(usbd_xfer_handle xfer,
213 						usbd_status status);
214 
215 Static usbd_status	ehci_device_request(usbd_xfer_handle xfer);
216 
217 Static usbd_status	ehci_device_setintr(ehci_softc_t *, ehci_soft_qh_t *,
218 			    int ival);
219 
220 Static void		ehci_add_qh(ehci_softc_t *, ehci_soft_qh_t *,
221 				    ehci_soft_qh_t *);
222 Static void		ehci_rem_qh(ehci_softc_t *, ehci_soft_qh_t *,
223 				    ehci_soft_qh_t *);
224 Static void		ehci_set_qh_qtd(ehci_soft_qh_t *, ehci_soft_qtd_t *);
225 Static void		ehci_sync_hc(ehci_softc_t *);
226 
227 Static void		ehci_close_pipe(usbd_pipe_handle, ehci_soft_qh_t *);
228 Static void		ehci_abort_xfer(usbd_xfer_handle, usbd_status);
229 
230 #ifdef EHCI_DEBUG
231 Static void		ehci_dump_regs(ehci_softc_t *);
232 void			ehci_dump(void);
233 Static ehci_softc_t 	*theehci;
234 Static void		ehci_dump_link(ehci_link_t, int);
235 Static void		ehci_dump_sqtds(ehci_soft_qtd_t *);
236 Static void		ehci_dump_sqtd(ehci_soft_qtd_t *);
237 Static void		ehci_dump_qtd(ehci_qtd_t *);
238 Static void		ehci_dump_sqh(ehci_soft_qh_t *);
239 #if notyet
240 Static void		ehci_dump_sitd(struct ehci_soft_itd *itd);
241 Static void		ehci_dump_itd(struct ehci_soft_itd *);
242 #endif
243 #ifdef DIAGNOSTIC
244 Static void		ehci_dump_exfer(struct ehci_xfer *);
245 #endif
246 #endif
247 
248 #define EHCI_NULL htole32(EHCI_LINK_TERMINATE)
249 
250 #define EHCI_INTR_ENDPT 1
251 
252 #define ehci_add_intr_list(sc, ex) \
253 	TAILQ_INSERT_TAIL(&(sc)->sc_intrhead, (ex), inext);
254 #define ehci_del_intr_list(sc, ex) \
255 	do { \
256 		TAILQ_REMOVE(&sc->sc_intrhead, (ex), inext); \
257 		(ex)->inext.tqe_prev = NULL; \
258 	} while (0)
259 #define ehci_active_intr_list(ex) ((ex)->inext.tqe_prev != NULL)
260 
261 Static const struct usbd_bus_methods ehci_bus_methods = {
262 	.open_pipe =	ehci_open,
263 	.soft_intr =	ehci_softintr,
264 	.do_poll =	ehci_poll,
265 	.allocm =	ehci_allocm,
266 	.freem =	ehci_freem,
267 	.allocx =	ehci_allocx,
268 	.freex =	ehci_freex,
269 	.get_lock =	ehci_get_lock,
270 };
271 
272 Static const struct usbd_pipe_methods ehci_root_ctrl_methods = {
273 	.transfer =	ehci_root_ctrl_transfer,
274 	.start =	ehci_root_ctrl_start,
275 	.abort =	ehci_root_ctrl_abort,
276 	.close =	ehci_root_ctrl_close,
277 	.cleartoggle =	ehci_noop,
278 	.done =		ehci_root_ctrl_done,
279 };
280 
281 Static const struct usbd_pipe_methods ehci_root_intr_methods = {
282 	.transfer =	ehci_root_intr_transfer,
283 	.start =	ehci_root_intr_start,
284 	.abort =	ehci_root_intr_abort,
285 	.close =	ehci_root_intr_close,
286 	.cleartoggle =	ehci_noop,
287 	.done =		ehci_root_intr_done,
288 };
289 
290 Static const struct usbd_pipe_methods ehci_device_ctrl_methods = {
291 	.transfer =	ehci_device_ctrl_transfer,
292 	.start =	ehci_device_ctrl_start,
293 	.abort =	ehci_device_ctrl_abort,
294 	.close =	ehci_device_ctrl_close,
295 	.cleartoggle =	ehci_noop,
296 	.done =		ehci_device_ctrl_done,
297 };
298 
299 Static const struct usbd_pipe_methods ehci_device_intr_methods = {
300 	.transfer =	ehci_device_intr_transfer,
301 	.start =	ehci_device_intr_start,
302 	.abort =	ehci_device_intr_abort,
303 	.close =	ehci_device_intr_close,
304 	.cleartoggle =	ehci_device_clear_toggle,
305 	.done =		ehci_device_intr_done,
306 };
307 
308 Static const struct usbd_pipe_methods ehci_device_bulk_methods = {
309 	.transfer =	ehci_device_bulk_transfer,
310 	.start =	ehci_device_bulk_start,
311 	.abort =	ehci_device_bulk_abort,
312 	.close =	ehci_device_bulk_close,
313 	.cleartoggle =	ehci_device_clear_toggle,
314 	.done =		ehci_device_bulk_done,
315 };
316 
317 Static const struct usbd_pipe_methods ehci_device_isoc_methods = {
318 	.transfer =	ehci_device_isoc_transfer,
319 	.start =	ehci_device_isoc_start,
320 	.abort =	ehci_device_isoc_abort,
321 	.close =	ehci_device_isoc_close,
322 	.cleartoggle =	ehci_noop,
323 	.done =		ehci_device_isoc_done,
324 };
325 
326 static const uint8_t revbits[EHCI_MAX_POLLRATE] = {
327 0x00,0x40,0x20,0x60,0x10,0x50,0x30,0x70,0x08,0x48,0x28,0x68,0x18,0x58,0x38,0x78,
328 0x04,0x44,0x24,0x64,0x14,0x54,0x34,0x74,0x0c,0x4c,0x2c,0x6c,0x1c,0x5c,0x3c,0x7c,
329 0x02,0x42,0x22,0x62,0x12,0x52,0x32,0x72,0x0a,0x4a,0x2a,0x6a,0x1a,0x5a,0x3a,0x7a,
330 0x06,0x46,0x26,0x66,0x16,0x56,0x36,0x76,0x0e,0x4e,0x2e,0x6e,0x1e,0x5e,0x3e,0x7e,
331 0x01,0x41,0x21,0x61,0x11,0x51,0x31,0x71,0x09,0x49,0x29,0x69,0x19,0x59,0x39,0x79,
332 0x05,0x45,0x25,0x65,0x15,0x55,0x35,0x75,0x0d,0x4d,0x2d,0x6d,0x1d,0x5d,0x3d,0x7d,
333 0x03,0x43,0x23,0x63,0x13,0x53,0x33,0x73,0x0b,0x4b,0x2b,0x6b,0x1b,0x5b,0x3b,0x7b,
334 0x07,0x47,0x27,0x67,0x17,0x57,0x37,0x77,0x0f,0x4f,0x2f,0x6f,0x1f,0x5f,0x3f,0x7f,
335 };
336 
337 usbd_status
338 ehci_init(ehci_softc_t *sc)
339 {
340 	u_int32_t vers, sparams, cparams, hcr;
341 	u_int i;
342 	usbd_status err;
343 	ehci_soft_qh_t *sqh;
344 	u_int ncomp;
345 
346 	DPRINTF(("ehci_init: start\n"));
347 #ifdef EHCI_DEBUG
348 	theehci = sc;
349 #endif
350 
351 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
352 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_SCHED);
353 	cv_init(&sc->sc_softwake_cv, "ehciab");
354 	cv_init(&sc->sc_doorbell, "ehcidi");
355 
356 	sc->sc_xferpool = pool_cache_init(sizeof(struct ehci_xfer), 0, 0, 0,
357 	    "ehcixfer", NULL, IPL_USB, NULL, NULL, NULL);
358 
359 	sc->sc_doorbell_si = softint_establish(SOFTINT_NET | SOFTINT_MPSAFE,
360 	    ehci_doorbell, sc);
361 	sc->sc_pcd_si = softint_establish(SOFTINT_NET | SOFTINT_MPSAFE,
362 	    ehci_pcd, sc);
363 
364 	sc->sc_offs = EREAD1(sc, EHCI_CAPLENGTH);
365 
366 	vers = EREAD2(sc, EHCI_HCIVERSION);
367 	aprint_verbose("%s: EHCI version %x.%x\n", device_xname(sc->sc_dev),
368 	       vers >> 8, vers & 0xff);
369 
370 	sparams = EREAD4(sc, EHCI_HCSPARAMS);
371 	DPRINTF(("ehci_init: sparams=0x%x\n", sparams));
372 	sc->sc_npcomp = EHCI_HCS_N_PCC(sparams);
373 	ncomp = EHCI_HCS_N_CC(sparams);
374 	if (ncomp != sc->sc_ncomp) {
375 		aprint_verbose("%s: wrong number of companions (%d != %d)\n",
376 			       device_xname(sc->sc_dev), ncomp, sc->sc_ncomp);
377 #if NOHCI == 0 || NUHCI == 0
378 		aprint_error("%s: ohci or uhci probably not configured\n",
379 			     device_xname(sc->sc_dev));
380 #endif
381 		if (ncomp < sc->sc_ncomp)
382 			sc->sc_ncomp = ncomp;
383 	}
384 	if (sc->sc_ncomp > 0) {
385 		KASSERT(!(sc->sc_flags & EHCIF_ETTF));
386 		aprint_normal("%s: companion controller%s, %d port%s each:",
387 		    device_xname(sc->sc_dev), sc->sc_ncomp!=1 ? "s" : "",
388 		    EHCI_HCS_N_PCC(sparams),
389 		    EHCI_HCS_N_PCC(sparams)!=1 ? "s" : "");
390 		for (i = 0; i < sc->sc_ncomp; i++)
391 			aprint_normal(" %s", device_xname(sc->sc_comps[i]));
392 		aprint_normal("\n");
393 	}
394 	sc->sc_noport = EHCI_HCS_N_PORTS(sparams);
395 	cparams = EREAD4(sc, EHCI_HCCPARAMS);
396 	DPRINTF(("ehci_init: cparams=0x%x\n", cparams));
397 	sc->sc_hasppc = EHCI_HCS_PPC(sparams);
398 
399 	if (EHCI_HCC_64BIT(cparams)) {
400 		/* MUST clear segment register if 64 bit capable. */
401 		EWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);
402 	}
403 
404 	sc->sc_bus.usbrev = USBREV_2_0;
405 
406 	usb_setup_reserve(sc->sc_dev, &sc->sc_dma_reserve, sc->sc_bus.dmatag,
407 	    USB_MEM_RESERVE);
408 
409 	/* Reset the controller */
410 	DPRINTF(("%s: resetting\n", device_xname(sc->sc_dev)));
411 	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
412 	usb_delay_ms(&sc->sc_bus, 1);
413 	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
414 	for (i = 0; i < 100; i++) {
415 		usb_delay_ms(&sc->sc_bus, 1);
416 		hcr = EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_HCRESET;
417 		if (!hcr)
418 			break;
419 	}
420 	if (hcr) {
421 		aprint_error("%s: reset timeout\n", device_xname(sc->sc_dev));
422 		return (USBD_IOERROR);
423 	}
424 	if (sc->sc_vendor_init)
425 		sc->sc_vendor_init(sc);
426 
427 	/*
428 	 * If we are doing embedded transaction translation function, force
429 	 * the controller to host mode.
430 	 */
431 	if (sc->sc_flags & EHCIF_ETTF) {
432 		uint32_t usbmode = EREAD4(sc, EHCI_USBMODE);
433 		usbmode &= ~EHCI_USBMODE_CM;
434 		usbmode |= EHCI_USBMODE_CM_HOST;
435 		EWRITE4(sc, EHCI_USBMODE, usbmode);
436 	}
437 
438 	/* XXX need proper intr scheduling */
439 	sc->sc_rand = 96;
440 
441 	/* frame list size at default, read back what we got and use that */
442 	switch (EHCI_CMD_FLS(EOREAD4(sc, EHCI_USBCMD))) {
443 	case 0: sc->sc_flsize = 1024; break;
444 	case 1: sc->sc_flsize = 512; break;
445 	case 2: sc->sc_flsize = 256; break;
446 	case 3: return (USBD_IOERROR);
447 	}
448 	err = usb_allocmem(&sc->sc_bus, sc->sc_flsize * sizeof(ehci_link_t),
449 	    EHCI_FLALIGN_ALIGN, &sc->sc_fldma);
450 	if (err)
451 		return (err);
452 	DPRINTF(("%s: flsize=%d\n", device_xname(sc->sc_dev),sc->sc_flsize));
453 	sc->sc_flist = KERNADDR(&sc->sc_fldma, 0);
454 
455 	for (i = 0; i < sc->sc_flsize; i++) {
456 		sc->sc_flist[i] = EHCI_NULL;
457 	}
458 
459 	EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));
460 
461 	sc->sc_softitds = kmem_zalloc(sc->sc_flsize * sizeof(ehci_soft_itd_t *),
462 				     KM_SLEEP);
463 	if (sc->sc_softitds == NULL)
464 		return ENOMEM;
465 	LIST_INIT(&sc->sc_freeitds);
466 	TAILQ_INIT(&sc->sc_intrhead);
467 
468 	/* Set up the bus struct. */
469 	sc->sc_bus.methods = &ehci_bus_methods;
470 	sc->sc_bus.pipe_size = sizeof(struct ehci_pipe);
471 
472 	sc->sc_eintrs = EHCI_NORMAL_INTRS;
473 
474 	/*
475 	 * Allocate the interrupt dummy QHs. These are arranged to give poll
476 	 * intervals that are powers of 2 times 1ms.
477 	 */
478 	for (i = 0; i < EHCI_INTRQHS; i++) {
479 		sqh = ehci_alloc_sqh(sc);
480 		if (sqh == NULL) {
481 			err = USBD_NOMEM;
482 			goto bad1;
483 		}
484 		sc->sc_islots[i].sqh = sqh;
485 	}
486 	for (i = 0; i < EHCI_INTRQHS; i++) {
487 		sqh = sc->sc_islots[i].sqh;
488 		if (i == 0) {
489 			/* The last (1ms) QH terminates. */
490 			sqh->qh.qh_link = EHCI_NULL;
491 			sqh->next = NULL;
492 		} else {
493 			/* Otherwise the next QH has half the poll interval */
494 			sqh->next = sc->sc_islots[(i + 1) / 2 - 1].sqh;
495 			sqh->qh.qh_link = htole32(sqh->next->physaddr |
496 			    EHCI_LINK_QH);
497 		}
498 		sqh->qh.qh_endp = htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH));
499 		sqh->qh.qh_curqtd = EHCI_NULL;
500 		sqh->next = NULL;
501 		sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
502 		sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
503 		sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
504 		sqh->sqtd = NULL;
505 		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
506 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
507 	}
508 	/* Point the frame list at the last level (128ms). */
509 	for (i = 0; i < sc->sc_flsize; i++) {
510 		int j;
511 
512 		j = (i & ~(EHCI_MAX_POLLRATE-1)) |
513 		    revbits[i & (EHCI_MAX_POLLRATE-1)];
514 		sc->sc_flist[j] = htole32(EHCI_LINK_QH |
515 		    sc->sc_islots[EHCI_IQHIDX(EHCI_IPOLLRATES - 1,
516 		    i)].sqh->physaddr);
517 	}
518 	usb_syncmem(&sc->sc_fldma, 0, sc->sc_flsize * sizeof(ehci_link_t),
519 	    BUS_DMASYNC_PREWRITE);
520 
521 	/* Allocate dummy QH that starts the async list. */
522 	sqh = ehci_alloc_sqh(sc);
523 	if (sqh == NULL) {
524 		err = USBD_NOMEM;
525 		goto bad1;
526 	}
527 	/* Fill the QH */
528 	sqh->qh.qh_endp =
529 	    htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH) | EHCI_QH_HRECL);
530 	sqh->qh.qh_link =
531 	    htole32(sqh->physaddr | EHCI_LINK_QH);
532 	sqh->qh.qh_curqtd = EHCI_NULL;
533 	sqh->next = NULL;
534 	/* Fill the overlay qTD */
535 	sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
536 	sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
537 	sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
538 	sqh->sqtd = NULL;
539 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
540 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
541 #ifdef EHCI_DEBUG
542 	if (ehcidebug) {
543 		ehci_dump_sqh(sqh);
544 	}
545 #endif
546 
547 	/* Point to async list */
548 	sc->sc_async_head = sqh;
549 	EOWRITE4(sc, EHCI_ASYNCLISTADDR, sqh->physaddr | EHCI_LINK_QH);
550 
551 	callout_init(&sc->sc_tmo_intrlist, CALLOUT_MPSAFE);
552 
553 	/* Turn on controller */
554 	EOWRITE4(sc, EHCI_USBCMD,
555 		 EHCI_CMD_ITC_2 | /* 2 microframes interrupt delay */
556 		 (EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_FLS_M) |
557 		 EHCI_CMD_ASE |
558 		 EHCI_CMD_PSE |
559 		 EHCI_CMD_RS);
560 
561 	/* Take over port ownership */
562 	EOWRITE4(sc, EHCI_CONFIGFLAG, EHCI_CONF_CF);
563 
564 	for (i = 0; i < 100; i++) {
565 		usb_delay_ms(&sc->sc_bus, 1);
566 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
567 		if (!hcr)
568 			break;
569 	}
570 	if (hcr) {
571 		aprint_error("%s: run timeout\n", device_xname(sc->sc_dev));
572 		return (USBD_IOERROR);
573 	}
574 
575 	/* Enable interrupts */
576 	DPRINTFN(1,("ehci_init: enabling\n"));
577 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
578 
579 	return (USBD_NORMAL_COMPLETION);
580 
581 #if 0
582  bad2:
583 	ehci_free_sqh(sc, sc->sc_async_head);
584 #endif
585  bad1:
586 	usb_freemem(&sc->sc_bus, &sc->sc_fldma);
587 	return (err);
588 }
589 
590 int
591 ehci_intr(void *v)
592 {
593 	ehci_softc_t *sc = v;
594 	int ret = 0;
595 
596 	if (sc == NULL)
597 		return 0;
598 
599 	mutex_spin_enter(&sc->sc_intr_lock);
600 
601 	if (sc->sc_dying || !device_has_power(sc->sc_dev))
602 		goto done;
603 
604 	/* If we get an interrupt while polling, then just ignore it. */
605 	if (sc->sc_bus.use_polling) {
606 		u_int32_t intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
607 
608 		if (intrs)
609 			EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
610 #ifdef DIAGNOSTIC
611 		DPRINTFN(16, ("ehci_intr: ignored interrupt while polling\n"));
612 #endif
613 		goto done;
614 	}
615 
616 	ret = ehci_intr1(sc);
617 
618 done:
619 	mutex_spin_exit(&sc->sc_intr_lock);
620 	return ret;
621 }
622 
623 Static int
624 ehci_intr1(ehci_softc_t *sc)
625 {
626 	u_int32_t intrs, eintrs;
627 
628 	DPRINTFN(20,("ehci_intr1: enter\n"));
629 
630 	/* In case the interrupt occurs before initialization has completed. */
631 	if (sc == NULL) {
632 #ifdef DIAGNOSTIC
633 		printf("ehci_intr1: sc == NULL\n");
634 #endif
635 		return (0);
636 	}
637 
638 	KASSERT(mutex_owned(&sc->sc_intr_lock));
639 
640 	intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
641 	if (!intrs)
642 		return (0);
643 
644 	eintrs = intrs & sc->sc_eintrs;
645 	DPRINTFN(7, ("ehci_intr1: sc=%p intrs=0x%x(0x%x) eintrs=0x%x\n",
646 		     sc, (u_int)intrs, EOREAD4(sc, EHCI_USBSTS),
647 		     (u_int)eintrs));
648 	if (!eintrs)
649 		return (0);
650 
651 	EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
652 	sc->sc_bus.no_intrs++;
653 	if (eintrs & EHCI_STS_IAA) {
654 		DPRINTF(("ehci_intr1: door bell\n"));
655 		kpreempt_disable();
656 		softint_schedule(sc->sc_doorbell_si);
657 		kpreempt_enable();
658 		eintrs &= ~EHCI_STS_IAA;
659 	}
660 	if (eintrs & (EHCI_STS_INT | EHCI_STS_ERRINT)) {
661 		DPRINTFN(5,("ehci_intr1: %s %s\n",
662 			    eintrs & EHCI_STS_INT ? "INT" : "",
663 			    eintrs & EHCI_STS_ERRINT ? "ERRINT" : ""));
664 		usb_schedsoftintr(&sc->sc_bus);
665 		eintrs &= ~(EHCI_STS_INT | EHCI_STS_ERRINT);
666 	}
667 	if (eintrs & EHCI_STS_HSE) {
668 		printf("%s: unrecoverable error, controller halted\n",
669 		       device_xname(sc->sc_dev));
670 		/* XXX what else */
671 	}
672 	if (eintrs & EHCI_STS_PCD) {
673 		kpreempt_disable();
674 		softint_schedule(sc->sc_pcd_si);
675 		kpreempt_enable();
676 		eintrs &= ~EHCI_STS_PCD;
677 	}
678 
679 	if (eintrs != 0) {
680 		/* Block unprocessed interrupts. */
681 		sc->sc_eintrs &= ~eintrs;
682 		EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
683 		printf("%s: blocking intrs 0x%x\n",
684 		       device_xname(sc->sc_dev), eintrs);
685 	}
686 
687 	return (1);
688 }
689 
690 Static void
691 ehci_doorbell(void *addr)
692 {
693 	ehci_softc_t *sc = addr;
694 
695 	mutex_enter(&sc->sc_lock);
696 	cv_broadcast(&sc->sc_doorbell);
697 	mutex_exit(&sc->sc_lock);
698 }
699 
700 Static void
701 ehci_pcd(void *addr)
702 {
703 	ehci_softc_t *sc = addr;
704 	usbd_xfer_handle xfer;
705 	usbd_pipe_handle pipe;
706 	u_char *p;
707 	int i, m;
708 
709 	mutex_enter(&sc->sc_lock);
710 	xfer = sc->sc_intrxfer;
711 
712 	if (xfer == NULL) {
713 		/* Just ignore the change. */
714 		goto done;
715 	}
716 
717 	pipe = xfer->pipe;
718 
719 	p = KERNADDR(&xfer->dmabuf, 0);
720 	m = min(sc->sc_noport, xfer->length * 8 - 1);
721 	memset(p, 0, xfer->length);
722 	for (i = 1; i <= m; i++) {
723 		/* Pick out CHANGE bits from the status reg. */
724 		if (EOREAD4(sc, EHCI_PORTSC(i)) & EHCI_PS_CLEAR)
725 			p[i/8] |= 1 << (i%8);
726 	}
727 	DPRINTF(("ehci_pcd: change=0x%02x\n", *p));
728 	xfer->actlen = xfer->length;
729 	xfer->status = USBD_NORMAL_COMPLETION;
730 
731 	usb_transfer_complete(xfer);
732 
733 done:
734 	mutex_exit(&sc->sc_lock);
735 }
736 
737 Static void
738 ehci_softintr(void *v)
739 {
740 	struct usbd_bus *bus = v;
741 	ehci_softc_t *sc = bus->hci_private;
742 	struct ehci_xfer *ex, *nextex;
743 
744 	KASSERT(sc->sc_bus.use_polling || mutex_owned(&sc->sc_lock));
745 
746 	DPRINTFN(10,("%s: ehci_softintr\n", device_xname(sc->sc_dev)));
747 
748 	/*
749 	 * The only explanation I can think of for why EHCI is as brain dead
750 	 * as UHCI interrupt-wise is that Intel was involved in both.
751 	 * An interrupt just tells us that something is done, we have no
752 	 * clue what, so we need to scan through all active transfers. :-(
753 	 */
754 	for (ex = TAILQ_FIRST(&sc->sc_intrhead); ex; ex = nextex) {
755 		nextex = TAILQ_NEXT(ex, inext);
756 		ehci_check_intr(sc, ex);
757 	}
758 
759 	/* Schedule a callout to catch any dropped transactions. */
760 	if ((sc->sc_flags & EHCIF_DROPPED_INTR_WORKAROUND) &&
761 	    !TAILQ_EMPTY(&sc->sc_intrhead))
762 		callout_reset(&sc->sc_tmo_intrlist,
763 		    hz, ehci_intrlist_timeout, sc);
764 
765 	if (sc->sc_softwake) {
766 		sc->sc_softwake = 0;
767 		cv_broadcast(&sc->sc_softwake_cv);
768 	}
769 }
770 
771 /* Check for an interrupt. */
772 Static void
773 ehci_check_intr(ehci_softc_t *sc, struct ehci_xfer *ex)
774 {
775 	int attr;
776 
777 	DPRINTFN(/*15*/2, ("ehci_check_intr: ex=%p\n", ex));
778 
779 	KASSERT(mutex_owned(&sc->sc_lock));
780 
781 	attr = ex->xfer.pipe->endpoint->edesc->bmAttributes;
782 	if (UE_GET_XFERTYPE(attr) == UE_ISOCHRONOUS)
783 		ehci_check_itd_intr(sc, ex);
784 	else
785 		ehci_check_qh_intr(sc, ex);
786 
787 	return;
788 }
789 
790 Static void
791 ehci_check_qh_intr(ehci_softc_t *sc, struct ehci_xfer *ex)
792 {
793 	ehci_soft_qtd_t *sqtd, *lsqtd;
794 	__uint32_t status;
795 
796 	KASSERT(mutex_owned(&sc->sc_lock));
797 
798 	if (ex->sqtdstart == NULL) {
799 		printf("ehci_check_qh_intr: not valid sqtd\n");
800 		return;
801 	}
802 
803 	lsqtd = ex->sqtdend;
804 #ifdef DIAGNOSTIC
805 	if (lsqtd == NULL) {
806 		printf("ehci_check_qh_intr: lsqtd==0\n");
807 		return;
808 	}
809 #endif
810 	/*
811 	 * If the last TD is still active we need to check whether there
812 	 * is a an error somewhere in the middle, or whether there was a
813 	 * short packet (SPD and not ACTIVE).
814 	 */
815 	usb_syncmem(&lsqtd->dma,
816 	    lsqtd->offs + offsetof(ehci_qtd_t, qtd_status),
817 	    sizeof(lsqtd->qtd.qtd_status),
818 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
819 	status = le32toh(lsqtd->qtd.qtd_status);
820 	usb_syncmem(&lsqtd->dma,
821 	    lsqtd->offs + offsetof(ehci_qtd_t, qtd_status),
822 	    sizeof(lsqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
823 	if (status & EHCI_QTD_ACTIVE) {
824 		DPRINTFN(12, ("ehci_check_intr: active ex=%p\n", ex));
825 		for (sqtd = ex->sqtdstart; sqtd != lsqtd; sqtd=sqtd->nextqtd) {
826 			usb_syncmem(&sqtd->dma,
827 			    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
828 			    sizeof(sqtd->qtd.qtd_status),
829 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
830 			status = le32toh(sqtd->qtd.qtd_status);
831 			usb_syncmem(&sqtd->dma,
832 			    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
833 			    sizeof(sqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
834 			/* If there's an active QTD the xfer isn't done. */
835 			if (status & EHCI_QTD_ACTIVE)
836 				break;
837 			/* Any kind of error makes the xfer done. */
838 			if (status & EHCI_QTD_HALTED)
839 				goto done;
840 			/* We want short packets, and it is short: it's done */
841 			if (EHCI_QTD_GET_BYTES(status) != 0)
842 				goto done;
843 		}
844 		DPRINTFN(12, ("ehci_check_intr: ex=%p std=%p still active\n",
845 			      ex, ex->sqtdstart));
846 		return;
847 	}
848  done:
849 	DPRINTFN(12, ("ehci_check_intr: ex=%p done\n", ex));
850 	callout_stop(&ex->xfer.timeout_handle);
851 	ehci_idone(ex);
852 }
853 
854 Static void
855 ehci_check_itd_intr(ehci_softc_t *sc, struct ehci_xfer *ex)
856 {
857 	ehci_soft_itd_t *itd;
858 	int i;
859 
860 	KASSERT(mutex_owned(&sc->sc_lock));
861 
862 	if (&ex->xfer != SIMPLEQ_FIRST(&ex->xfer.pipe->queue))
863 		return;
864 
865 	if (ex->itdstart == NULL) {
866 		printf("ehci_check_itd_intr: not valid itd\n");
867 		return;
868 	}
869 
870 	itd = ex->itdend;
871 #ifdef DIAGNOSTIC
872 	if (itd == NULL) {
873 		printf("ehci_check_itd_intr: itdend == 0\n");
874 		return;
875 	}
876 #endif
877 
878 	/*
879 	 * check no active transfers in last itd, meaning we're finished
880 	 */
881 
882 	usb_syncmem(&itd->dma, itd->offs + offsetof(ehci_itd_t, itd_ctl),
883 		    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_POSTWRITE |
884 		    BUS_DMASYNC_POSTREAD);
885 
886 	for (i = 0; i < EHCI_ITD_NUFRAMES; i++) {
887 		if (le32toh(itd->itd.itd_ctl[i]) & EHCI_ITD_ACTIVE)
888 			break;
889 	}
890 
891 	if (i == EHCI_ITD_NUFRAMES) {
892 		goto done; /* All 8 descriptors inactive, it's done */
893 	}
894 
895 	DPRINTFN(12, ("ehci_check_itd_intr: ex %p itd %p still active\n", ex,
896 			ex->itdstart));
897 	return;
898 done:
899 	DPRINTFN(12, ("ehci_check_itd_intr: ex=%p done\n", ex));
900 	callout_stop(&ex->xfer.timeout_handle);
901 	ehci_idone(ex);
902 }
903 
904 Static void
905 ehci_idone(struct ehci_xfer *ex)
906 {
907 	usbd_xfer_handle xfer = &ex->xfer;
908 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
909 	struct ehci_softc *sc = xfer->pipe->device->bus->hci_private;
910 	ehci_soft_qtd_t *sqtd, *lsqtd;
911 	u_int32_t status = 0, nstatus = 0;
912 	int actlen;
913 
914 	KASSERT(mutex_owned(&sc->sc_lock));
915 
916 	DPRINTFN(/*12*/2, ("ehci_idone: ex=%p\n", ex));
917 
918 #ifdef DIAGNOSTIC
919 	{
920 		if (ex->isdone) {
921 #ifdef EHCI_DEBUG
922 			printf("ehci_idone: ex is done!\n   ");
923 			ehci_dump_exfer(ex);
924 #else
925 			printf("ehci_idone: ex=%p is done!\n", ex);
926 #endif
927 			return;
928 		}
929 		ex->isdone = 1;
930 	}
931 #endif
932 	if (xfer->status == USBD_CANCELLED ||
933 	    xfer->status == USBD_TIMEOUT) {
934 		DPRINTF(("ehci_idone: aborted xfer=%p\n", xfer));
935 		return;
936 	}
937 
938 #ifdef EHCI_DEBUG
939 	DPRINTFN(/*10*/2, ("ehci_idone: xfer=%p, pipe=%p ready\n", xfer, epipe));
940 	if (ehcidebug > 10)
941 		ehci_dump_sqtds(ex->sqtdstart);
942 #endif
943 
944 	/* The transfer is done, compute actual length and status. */
945 
946 	if (UE_GET_XFERTYPE(xfer->pipe->endpoint->edesc->bmAttributes)
947 				== UE_ISOCHRONOUS) {
948 		/* Isoc transfer */
949 		struct ehci_soft_itd *itd;
950 		int i, nframes, len, uframes;
951 
952 		nframes = 0;
953 		actlen = 0;
954 
955 		i = xfer->pipe->endpoint->edesc->bInterval;
956 		uframes = min(1 << (i - 1), USB_UFRAMES_PER_FRAME);
957 
958 		for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
959 			usb_syncmem(&itd->dma,itd->offs + offsetof(ehci_itd_t,itd_ctl),
960 			    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_POSTWRITE |
961 			    BUS_DMASYNC_POSTREAD);
962 
963 			for (i = 0; i < EHCI_ITD_NUFRAMES; i += uframes) {
964 				/* XXX - driver didn't fill in the frame full
965 				 *   of uframes. This leads to scheduling
966 				 *   inefficiencies, but working around
967 				 *   this doubles complexity of tracking
968 				 *   an xfer.
969 				 */
970 				if (nframes >= xfer->nframes)
971 					break;
972 
973 				status = le32toh(itd->itd.itd_ctl[i]);
974 				len = EHCI_ITD_GET_LEN(status);
975 				if (EHCI_ITD_GET_STATUS(status) != 0)
976 					len = 0; /*No valid data on error*/
977 
978 				xfer->frlengths[nframes++] = len;
979 				actlen += len;
980 			}
981 
982 			if (nframes >= xfer->nframes)
983 				break;
984 	    	}
985 
986 		xfer->actlen = actlen;
987 		xfer->status = USBD_NORMAL_COMPLETION;
988 		goto end;
989 	}
990 
991 	/* Continue processing xfers using queue heads */
992 
993 	lsqtd = ex->sqtdend;
994 	actlen = 0;
995 	for (sqtd = ex->sqtdstart; sqtd != lsqtd->nextqtd; sqtd = sqtd->nextqtd) {
996 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
997 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
998 		nstatus = le32toh(sqtd->qtd.qtd_status);
999 		if (nstatus & EHCI_QTD_ACTIVE)
1000 			break;
1001 
1002 		status = nstatus;
1003 		if (EHCI_QTD_GET_PID(status) != EHCI_QTD_PID_SETUP)
1004 			actlen += sqtd->len - EHCI_QTD_GET_BYTES(status);
1005 	}
1006 
1007 
1008 	/*
1009 	 * If there are left over TDs we need to update the toggle.
1010 	 * The default pipe doesn't need it since control transfers
1011 	 * start the toggle at 0 every time.
1012 	 * For a short transfer we need to update the toggle for the missing
1013 	 * packets within the qTD.
1014 	 */
1015 	if ((sqtd != lsqtd->nextqtd || EHCI_QTD_GET_BYTES(status)) &&
1016 	    xfer->pipe->device->default_pipe != xfer->pipe) {
1017 		DPRINTFN(2, ("ehci_idone: need toggle update "
1018 			     "status=%08x nstatus=%08x\n", status, nstatus));
1019 #if 0
1020 		ehci_dump_sqh(epipe->sqh);
1021 		ehci_dump_sqtds(ex->sqtdstart);
1022 #endif
1023 		epipe->nexttoggle = EHCI_QTD_GET_TOGGLE(nstatus);
1024 	}
1025 
1026 	DPRINTFN(/*10*/2, ("ehci_idone: len=%d, actlen=%d, status=0x%x\n",
1027 			   xfer->length, actlen, status));
1028 	xfer->actlen = actlen;
1029 	if (status & EHCI_QTD_HALTED) {
1030 #ifdef EHCI_DEBUG
1031 		char sbuf[128];
1032 
1033 		snprintb(sbuf, sizeof(sbuf),
1034 		    "\20\7HALTED\6BUFERR\5BABBLE\4XACTERR\3MISSED\1PINGSTATE",
1035 		    (u_int32_t)status);
1036 
1037 		DPRINTFN(2, ("ehci_idone: error, addr=%d, endpt=0x%02x, "
1038 			  "status 0x%s\n",
1039 			  xfer->pipe->device->address,
1040 			  xfer->pipe->endpoint->edesc->bEndpointAddress,
1041 			  sbuf));
1042 		if (ehcidebug > 2) {
1043 			ehci_dump_sqh(epipe->sqh);
1044 			ehci_dump_sqtds(ex->sqtdstart);
1045 		}
1046 #endif
1047 		/* low&full speed has an extra error flag */
1048 		if (EHCI_QH_GET_EPS(epipe->sqh->qh.qh_endp) !=
1049 		    EHCI_QH_SPEED_HIGH)
1050 			status &= EHCI_QTD_STATERRS | EHCI_QTD_PINGSTATE;
1051 		else
1052 			status &= EHCI_QTD_STATERRS;
1053 		if (status == 0) /* no other errors means a stall */ {
1054 			xfer->status = USBD_STALLED;
1055 		} else {
1056 			xfer->status = USBD_IOERROR; /* more info XXX */
1057 		}
1058 		/* XXX need to reset TT on missed microframe */
1059 		if (status & EHCI_QTD_MISSEDMICRO) {
1060 			printf("%s: missed microframe, TT reset not "
1061 			    "implemented, hub might be inoperational\n",
1062 			    device_xname(sc->sc_dev));
1063 		}
1064 	} else {
1065 		xfer->status = USBD_NORMAL_COMPLETION;
1066 	}
1067 
1068     end:
1069 	/* XXX transfer_complete memcpys out transfer data (for in endpoints)
1070 	 * during this call, before methods->done is called: dma sync required
1071 	 * beforehand? */
1072 	usb_transfer_complete(xfer);
1073 	DPRINTFN(/*12*/2, ("ehci_idone: ex=%p done\n", ex));
1074 }
1075 
1076 /*
1077  * Wait here until controller claims to have an interrupt.
1078  * Then call ehci_intr and return.  Use timeout to avoid waiting
1079  * too long.
1080  */
1081 Static void
1082 ehci_waitintr(ehci_softc_t *sc, usbd_xfer_handle xfer)
1083 {
1084 	int timo;
1085 	u_int32_t intrs;
1086 
1087 	xfer->status = USBD_IN_PROGRESS;
1088 	for (timo = xfer->timeout; timo >= 0; timo--) {
1089 		usb_delay_ms(&sc->sc_bus, 1);
1090 		if (sc->sc_dying)
1091 			break;
1092 		intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS)) &
1093 			sc->sc_eintrs;
1094 		DPRINTFN(15,("ehci_waitintr: 0x%04x\n", intrs));
1095 #ifdef EHCI_DEBUG
1096 		if (ehcidebug > 15)
1097 			ehci_dump_regs(sc);
1098 #endif
1099 		if (intrs) {
1100 			mutex_spin_enter(&sc->sc_intr_lock);
1101 			ehci_intr1(sc);
1102 			mutex_spin_exit(&sc->sc_intr_lock);
1103 			if (xfer->status != USBD_IN_PROGRESS)
1104 				return;
1105 		}
1106 	}
1107 
1108 	/* Timeout */
1109 	DPRINTF(("ehci_waitintr: timeout\n"));
1110 	xfer->status = USBD_TIMEOUT;
1111 	mutex_enter(&sc->sc_lock);
1112 	usb_transfer_complete(xfer);
1113 	mutex_exit(&sc->sc_lock);
1114 	/* XXX should free TD */
1115 }
1116 
1117 Static void
1118 ehci_poll(struct usbd_bus *bus)
1119 {
1120 	ehci_softc_t *sc = bus->hci_private;
1121 #ifdef EHCI_DEBUG
1122 	static int last;
1123 	int new;
1124 	new = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
1125 	if (new != last) {
1126 		DPRINTFN(10,("ehci_poll: intrs=0x%04x\n", new));
1127 		last = new;
1128 	}
1129 #endif
1130 
1131 	if (EOREAD4(sc, EHCI_USBSTS) & sc->sc_eintrs) {
1132 		mutex_spin_enter(&sc->sc_intr_lock);
1133 		ehci_intr1(sc);
1134 		mutex_spin_exit(&sc->sc_intr_lock);
1135 	}
1136 }
1137 
1138 void
1139 ehci_childdet(device_t self, device_t child)
1140 {
1141 	struct ehci_softc *sc = device_private(self);
1142 
1143 	KASSERT(sc->sc_child == child);
1144 	sc->sc_child = NULL;
1145 }
1146 
1147 int
1148 ehci_detach(struct ehci_softc *sc, int flags)
1149 {
1150 	int rv = 0;
1151 
1152 	if (sc->sc_child != NULL)
1153 		rv = config_detach(sc->sc_child, flags);
1154 
1155 	if (rv != 0)
1156 		return (rv);
1157 
1158 	callout_halt(&sc->sc_tmo_intrlist, NULL);
1159 	callout_destroy(&sc->sc_tmo_intrlist);
1160 
1161 	/* XXX free other data structures XXX */
1162 	if (sc->sc_softitds)
1163 		kmem_free(sc->sc_softitds,
1164 		    sc->sc_flsize * sizeof(ehci_soft_itd_t *));
1165 	cv_destroy(&sc->sc_doorbell);
1166 	cv_destroy(&sc->sc_softwake_cv);
1167 
1168 #if 0
1169 	/* XXX destroyed in ehci_pci.c as it controls ehci_intr access */
1170 
1171 	softint_disestablish(sc->sc_doorbell_si);
1172 	softint_disestablish(sc->sc_pcd_si);
1173 
1174 	mutex_destroy(&sc->sc_lock);
1175 	mutex_destroy(&sc->sc_intr_lock);
1176 #endif
1177 
1178 	pool_cache_destroy(sc->sc_xferpool);
1179 
1180 	EOWRITE4(sc, EHCI_CONFIGFLAG, 0);
1181 
1182 	return (rv);
1183 }
1184 
1185 
1186 int
1187 ehci_activate(device_t self, enum devact act)
1188 {
1189 	struct ehci_softc *sc = device_private(self);
1190 
1191 	switch (act) {
1192 	case DVACT_DEACTIVATE:
1193 		sc->sc_dying = 1;
1194 		return 0;
1195 	default:
1196 		return EOPNOTSUPP;
1197 	}
1198 }
1199 
1200 /*
1201  * Handle suspend/resume.
1202  *
1203  * We need to switch to polling mode here, because this routine is
1204  * called from an interrupt context.  This is all right since we
1205  * are almost suspended anyway.
1206  *
1207  * Note that this power handler isn't to be registered directly; the
1208  * bus glue needs to call out to it.
1209  */
1210 bool
1211 ehci_suspend(device_t dv, const pmf_qual_t *qual)
1212 {
1213 	ehci_softc_t *sc = device_private(dv);
1214 	int i;
1215 	uint32_t cmd, hcr;
1216 
1217 	mutex_spin_enter(&sc->sc_intr_lock);
1218 	sc->sc_bus.use_polling++;
1219 	mutex_spin_exit(&sc->sc_intr_lock);
1220 
1221 	for (i = 1; i <= sc->sc_noport; i++) {
1222 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1223 		if ((cmd & EHCI_PS_PO) == 0 && (cmd & EHCI_PS_PE) == EHCI_PS_PE)
1224 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_SUSP);
1225 	}
1226 
1227 	sc->sc_cmd = EOREAD4(sc, EHCI_USBCMD);
1228 
1229 	cmd = sc->sc_cmd & ~(EHCI_CMD_ASE | EHCI_CMD_PSE);
1230 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1231 
1232 	for (i = 0; i < 100; i++) {
1233 		hcr = EOREAD4(sc, EHCI_USBSTS) & (EHCI_STS_ASS | EHCI_STS_PSS);
1234 		if (hcr == 0)
1235 			break;
1236 
1237 		usb_delay_ms(&sc->sc_bus, 1);
1238 	}
1239 	if (hcr != 0)
1240 		printf("%s: reset timeout\n", device_xname(dv));
1241 
1242 	cmd &= ~EHCI_CMD_RS;
1243 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1244 
1245 	for (i = 0; i < 100; i++) {
1246 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1247 		if (hcr == EHCI_STS_HCH)
1248 			break;
1249 
1250 		usb_delay_ms(&sc->sc_bus, 1);
1251 	}
1252 	if (hcr != EHCI_STS_HCH)
1253 		printf("%s: config timeout\n", device_xname(dv));
1254 
1255 	mutex_spin_enter(&sc->sc_intr_lock);
1256 	sc->sc_bus.use_polling--;
1257 	mutex_spin_exit(&sc->sc_intr_lock);
1258 
1259 	return true;
1260 }
1261 
1262 bool
1263 ehci_resume(device_t dv, const pmf_qual_t *qual)
1264 {
1265 	ehci_softc_t *sc = device_private(dv);
1266 	int i;
1267 	uint32_t cmd, hcr;
1268 
1269 	/* restore things in case the bios sucks */
1270 	EOWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);
1271 	EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));
1272 	EOWRITE4(sc, EHCI_ASYNCLISTADDR,
1273 	    sc->sc_async_head->physaddr | EHCI_LINK_QH);
1274 
1275 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs & ~EHCI_INTR_PCIE);
1276 
1277 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1278 
1279 	hcr = 0;
1280 	for (i = 1; i <= sc->sc_noport; i++) {
1281 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1282 		if ((cmd & EHCI_PS_PO) == 0 &&
1283 		    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP) {
1284 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_FPR);
1285 			hcr = 1;
1286 		}
1287 	}
1288 
1289 	if (hcr) {
1290 		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
1291 
1292 		for (i = 1; i <= sc->sc_noport; i++) {
1293 			cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1294 			if ((cmd & EHCI_PS_PO) == 0 &&
1295 			    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP)
1296 				EOWRITE4(sc, EHCI_PORTSC(i),
1297 				    cmd & ~EHCI_PS_FPR);
1298 		}
1299 	}
1300 
1301 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1302 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
1303 
1304 	for (i = 0; i < 100; i++) {
1305 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1306 		if (hcr != EHCI_STS_HCH)
1307 			break;
1308 
1309 		usb_delay_ms(&sc->sc_bus, 1);
1310 	}
1311 	if (hcr == EHCI_STS_HCH)
1312 		printf("%s: config timeout\n", device_xname(dv));
1313 
1314 	return true;
1315 }
1316 
1317 /*
1318  * Shut down the controller when the system is going down.
1319  */
1320 bool
1321 ehci_shutdown(device_t self, int flags)
1322 {
1323 	ehci_softc_t *sc = device_private(self);
1324 
1325 	DPRINTF(("ehci_shutdown: stopping the HC\n"));
1326 	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
1327 	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
1328 	return true;
1329 }
1330 
1331 Static usbd_status
1332 ehci_allocm(struct usbd_bus *bus, usb_dma_t *dma, u_int32_t size)
1333 {
1334 	struct ehci_softc *sc = bus->hci_private;
1335 	usbd_status err;
1336 
1337 	err = usb_allocmem_flags(&sc->sc_bus, size, 0, dma, USBMALLOC_MULTISEG);
1338 #ifdef EHCI_DEBUG
1339 	if (err)
1340 		printf("ehci_allocm: usb_allocmem_flags()= %s (%d)\n",
1341 			usbd_errstr(err), err);
1342 #endif
1343 	if (err == USBD_NOMEM)
1344 		err = usb_reserve_allocm(&sc->sc_dma_reserve, dma, size);
1345 #ifdef EHCI_DEBUG
1346 	if (err)
1347 		printf("ehci_allocm: usb_reserve_allocm()= %s (%d)\n",
1348 			usbd_errstr(err), err);
1349 #endif
1350 	return (err);
1351 }
1352 
1353 Static void
1354 ehci_freem(struct usbd_bus *bus, usb_dma_t *dma)
1355 {
1356 	struct ehci_softc *sc = bus->hci_private;
1357 
1358 	if (dma->block->flags & USB_DMA_RESERVE) {
1359 		usb_reserve_freem(&sc->sc_dma_reserve,
1360 		    dma);
1361 		return;
1362 	}
1363 	usb_freemem(&sc->sc_bus, dma);
1364 }
1365 
1366 Static usbd_xfer_handle
1367 ehci_allocx(struct usbd_bus *bus)
1368 {
1369 	struct ehci_softc *sc = bus->hci_private;
1370 	usbd_xfer_handle xfer;
1371 
1372 	xfer = pool_cache_get(sc->sc_xferpool, PR_NOWAIT);
1373 	if (xfer != NULL) {
1374 		memset(xfer, 0, sizeof(struct ehci_xfer));
1375 #ifdef DIAGNOSTIC
1376 		EXFER(xfer)->isdone = 1;
1377 		xfer->busy_free = XFER_BUSY;
1378 #endif
1379 	}
1380 	return (xfer);
1381 }
1382 
1383 Static void
1384 ehci_freex(struct usbd_bus *bus, usbd_xfer_handle xfer)
1385 {
1386 	struct ehci_softc *sc = bus->hci_private;
1387 
1388 #ifdef DIAGNOSTIC
1389 	if (xfer->busy_free != XFER_BUSY) {
1390 		printf("ehci_freex: xfer=%p not busy, 0x%08x\n", xfer,
1391 		       xfer->busy_free);
1392 	}
1393 	xfer->busy_free = XFER_FREE;
1394 	if (!EXFER(xfer)->isdone) {
1395 		printf("ehci_freex: !isdone\n");
1396 	}
1397 #endif
1398 	pool_cache_put(sc->sc_xferpool, xfer);
1399 }
1400 
1401 Static void
1402 ehci_get_lock(struct usbd_bus *bus, kmutex_t **lock)
1403 {
1404 	struct ehci_softc *sc = bus->hci_private;
1405 
1406 	*lock = &sc->sc_lock;
1407 }
1408 
1409 Static void
1410 ehci_device_clear_toggle(usbd_pipe_handle pipe)
1411 {
1412 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
1413 
1414 	DPRINTF(("ehci_device_clear_toggle: epipe=%p status=0x%x\n",
1415 		 epipe, epipe->sqh->qh.qh_qtd.qtd_status));
1416 #ifdef EHCI_DEBUG
1417 	if (ehcidebug)
1418 		usbd_dump_pipe(pipe);
1419 #endif
1420 	epipe->nexttoggle = 0;
1421 }
1422 
1423 Static void
1424 ehci_noop(usbd_pipe_handle pipe)
1425 {
1426 }
1427 
1428 #ifdef EHCI_DEBUG
1429 Static void
1430 ehci_dump_regs(ehci_softc_t *sc)
1431 {
1432 	int i;
1433 	printf("cmd=0x%08x, sts=0x%08x, ien=0x%08x\n",
1434 	       EOREAD4(sc, EHCI_USBCMD),
1435 	       EOREAD4(sc, EHCI_USBSTS),
1436 	       EOREAD4(sc, EHCI_USBINTR));
1437 	printf("frindex=0x%08x ctrdsegm=0x%08x periodic=0x%08x async=0x%08x\n",
1438 	       EOREAD4(sc, EHCI_FRINDEX),
1439 	       EOREAD4(sc, EHCI_CTRLDSSEGMENT),
1440 	       EOREAD4(sc, EHCI_PERIODICLISTBASE),
1441 	       EOREAD4(sc, EHCI_ASYNCLISTADDR));
1442 	for (i = 1; i <= sc->sc_noport; i++)
1443 		printf("port %d status=0x%08x\n", i,
1444 		       EOREAD4(sc, EHCI_PORTSC(i)));
1445 }
1446 
1447 /*
1448  * Unused function - this is meant to be called from a kernel
1449  * debugger.
1450  */
1451 void
1452 ehci_dump(void)
1453 {
1454 	ehci_dump_regs(theehci);
1455 }
1456 
1457 Static void
1458 ehci_dump_link(ehci_link_t link, int type)
1459 {
1460 	link = le32toh(link);
1461 	printf("0x%08x", link);
1462 	if (link & EHCI_LINK_TERMINATE)
1463 		printf("<T>");
1464 	else {
1465 		printf("<");
1466 		if (type) {
1467 			switch (EHCI_LINK_TYPE(link)) {
1468 			case EHCI_LINK_ITD: printf("ITD"); break;
1469 			case EHCI_LINK_QH: printf("QH"); break;
1470 			case EHCI_LINK_SITD: printf("SITD"); break;
1471 			case EHCI_LINK_FSTN: printf("FSTN"); break;
1472 			}
1473 		}
1474 		printf(">");
1475 	}
1476 }
1477 
1478 Static void
1479 ehci_dump_sqtds(ehci_soft_qtd_t *sqtd)
1480 {
1481 	int i;
1482 	u_int32_t stop;
1483 
1484 	stop = 0;
1485 	for (i = 0; sqtd && i < 20 && !stop; sqtd = sqtd->nextqtd, i++) {
1486 		ehci_dump_sqtd(sqtd);
1487 		usb_syncmem(&sqtd->dma,
1488 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1489 		    sizeof(sqtd->qtd),
1490 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1491 		stop = sqtd->qtd.qtd_next & htole32(EHCI_LINK_TERMINATE);
1492 		usb_syncmem(&sqtd->dma,
1493 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1494 		    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1495 	}
1496 	if (sqtd)
1497 		printf("dump aborted, too many TDs\n");
1498 }
1499 
1500 Static void
1501 ehci_dump_sqtd(ehci_soft_qtd_t *sqtd)
1502 {
1503 	usb_syncmem(&sqtd->dma, sqtd->offs,
1504 	    sizeof(sqtd->qtd), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1505 	printf("QTD(%p) at 0x%08x:\n", sqtd, sqtd->physaddr);
1506 	ehci_dump_qtd(&sqtd->qtd);
1507 	usb_syncmem(&sqtd->dma, sqtd->offs,
1508 	    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1509 }
1510 
1511 Static void
1512 ehci_dump_qtd(ehci_qtd_t *qtd)
1513 {
1514 	u_int32_t s;
1515 	char sbuf[128];
1516 
1517 	printf("  next="); ehci_dump_link(qtd->qtd_next, 0);
1518 	printf(" altnext="); ehci_dump_link(qtd->qtd_altnext, 0);
1519 	printf("\n");
1520 	s = le32toh(qtd->qtd_status);
1521 	snprintb(sbuf, sizeof(sbuf),
1522 	    "\20\10ACTIVE\7HALTED\6BUFERR\5BABBLE\4XACTERR"
1523 	    "\3MISSED\2SPLIT\1PING", EHCI_QTD_GET_STATUS(s));
1524 	printf("  status=0x%08x: toggle=%d bytes=0x%x ioc=%d c_page=0x%x\n",
1525 	       s, EHCI_QTD_GET_TOGGLE(s), EHCI_QTD_GET_BYTES(s),
1526 	       EHCI_QTD_GET_IOC(s), EHCI_QTD_GET_C_PAGE(s));
1527 	printf("    cerr=%d pid=%d stat=0x%s\n", EHCI_QTD_GET_CERR(s),
1528 	       EHCI_QTD_GET_PID(s), sbuf);
1529 	for (s = 0; s < 5; s++)
1530 		printf("  buffer[%d]=0x%08x\n", s, le32toh(qtd->qtd_buffer[s]));
1531 }
1532 
1533 Static void
1534 ehci_dump_sqh(ehci_soft_qh_t *sqh)
1535 {
1536 	ehci_qh_t *qh = &sqh->qh;
1537 	u_int32_t endp, endphub;
1538 
1539 	usb_syncmem(&sqh->dma, sqh->offs,
1540 	    sizeof(sqh->qh), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1541 	printf("QH(%p) at 0x%08x:\n", sqh, sqh->physaddr);
1542 	printf("  link="); ehci_dump_link(qh->qh_link, 1); printf("\n");
1543 	endp = le32toh(qh->qh_endp);
1544 	printf("  endp=0x%08x\n", endp);
1545 	printf("    addr=0x%02x inact=%d endpt=%d eps=%d dtc=%d hrecl=%d\n",
1546 	       EHCI_QH_GET_ADDR(endp), EHCI_QH_GET_INACT(endp),
1547 	       EHCI_QH_GET_ENDPT(endp),  EHCI_QH_GET_EPS(endp),
1548 	       EHCI_QH_GET_DTC(endp), EHCI_QH_GET_HRECL(endp));
1549 	printf("    mpl=0x%x ctl=%d nrl=%d\n",
1550 	       EHCI_QH_GET_MPL(endp), EHCI_QH_GET_CTL(endp),
1551 	       EHCI_QH_GET_NRL(endp));
1552 	endphub = le32toh(qh->qh_endphub);
1553 	printf("  endphub=0x%08x\n", endphub);
1554 	printf("    smask=0x%02x cmask=0x%02x huba=0x%02x port=%d mult=%d\n",
1555 	       EHCI_QH_GET_SMASK(endphub), EHCI_QH_GET_CMASK(endphub),
1556 	       EHCI_QH_GET_HUBA(endphub), EHCI_QH_GET_PORT(endphub),
1557 	       EHCI_QH_GET_MULT(endphub));
1558 	printf("  curqtd="); ehci_dump_link(qh->qh_curqtd, 0); printf("\n");
1559 	printf("Overlay qTD:\n");
1560 	ehci_dump_qtd(&qh->qh_qtd);
1561 	usb_syncmem(&sqh->dma, sqh->offs,
1562 	    sizeof(sqh->qh), BUS_DMASYNC_PREREAD);
1563 }
1564 
1565 #if notyet
1566 Static void
1567 ehci_dump_itd(struct ehci_soft_itd *itd)
1568 {
1569 	ehci_isoc_trans_t t;
1570 	ehci_isoc_bufr_ptr_t b, b2, b3;
1571 	int i;
1572 
1573 	printf("ITD: next phys=%X\n", itd->itd.itd_next);
1574 
1575 	for (i = 0; i < EHCI_ITD_NUFRAMES; i++) {
1576 		t = le32toh(itd->itd.itd_ctl[i]);
1577 		printf("ITDctl %d: stat=%X len=%X ioc=%X pg=%X offs=%X\n", i,
1578 		    EHCI_ITD_GET_STATUS(t), EHCI_ITD_GET_LEN(t),
1579 		    EHCI_ITD_GET_IOC(t), EHCI_ITD_GET_PG(t),
1580 		    EHCI_ITD_GET_OFFS(t));
1581 	}
1582 	printf("ITDbufr: ");
1583 	for (i = 0; i < EHCI_ITD_NBUFFERS; i++)
1584 		printf("%X,", EHCI_ITD_GET_BPTR(le32toh(itd->itd.itd_bufr[i])));
1585 
1586 	b = le32toh(itd->itd.itd_bufr[0]);
1587 	b2 = le32toh(itd->itd.itd_bufr[1]);
1588 	b3 = le32toh(itd->itd.itd_bufr[2]);
1589 	printf("\nep=%X daddr=%X dir=%d maxpkt=%X multi=%X\n",
1590 	    EHCI_ITD_GET_EP(b), EHCI_ITD_GET_DADDR(b), EHCI_ITD_GET_DIR(b2),
1591 	    EHCI_ITD_GET_MAXPKT(b2), EHCI_ITD_GET_MULTI(b3));
1592 }
1593 
1594 Static void
1595 ehci_dump_sitd(struct ehci_soft_itd *itd)
1596 {
1597 	printf("SITD %p next=%p prev=%p xfernext=%p physaddr=%X slot=%d\n",
1598 			itd, itd->u.frame_list.next, itd->u.frame_list.prev,
1599 			itd->xfer_next, itd->physaddr, itd->slot);
1600 }
1601 #endif
1602 
1603 #ifdef DIAGNOSTIC
1604 Static void
1605 ehci_dump_exfer(struct ehci_xfer *ex)
1606 {
1607 	printf("ehci_dump_exfer: ex=%p sqtdstart=%p end=%p itdstart=%p end=%p isdone=%d\n", ex, ex->sqtdstart, ex->sqtdend, ex->itdstart, ex->itdend, ex->isdone);
1608 }
1609 #endif
1610 #endif
1611 
1612 Static usbd_status
1613 ehci_open(usbd_pipe_handle pipe)
1614 {
1615 	usbd_device_handle dev = pipe->device;
1616 	ehci_softc_t *sc = dev->bus->hci_private;
1617 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1618 	u_int8_t addr = dev->address;
1619 	u_int8_t xfertype = ed->bmAttributes & UE_XFERTYPE;
1620 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
1621 	ehci_soft_qh_t *sqh;
1622 	usbd_status err;
1623 	int ival, speed, naks;
1624 	int hshubaddr, hshubport;
1625 
1626 	DPRINTFN(1, ("ehci_open: pipe=%p, addr=%d, endpt=%d (%d)\n",
1627 		     pipe, addr, ed->bEndpointAddress, sc->sc_addr));
1628 
1629 	if (dev->myhsport) {
1630 		/*
1631 		 * When directly attached FS/LS device while doing embedded
1632 		 * transaction translations and we are the hub, set the hub
1633 		 * address to 0 (us).
1634 		 */
1635 		if (!(sc->sc_flags & EHCIF_ETTF)
1636 		    || (dev->myhsport->parent->address != sc->sc_addr)) {
1637 			hshubaddr = dev->myhsport->parent->address;
1638 		} else {
1639 			hshubaddr = 0;
1640 		}
1641 		hshubport = dev->myhsport->portno;
1642 	} else {
1643 		hshubaddr = 0;
1644 		hshubport = 0;
1645 	}
1646 
1647 	if (sc->sc_dying)
1648 		return (USBD_IOERROR);
1649 
1650 	/* toggle state needed for bulk endpoints */
1651 	epipe->nexttoggle = pipe->endpoint->datatoggle;
1652 
1653 	if (addr == sc->sc_addr) {
1654 		switch (ed->bEndpointAddress) {
1655 		case USB_CONTROL_ENDPOINT:
1656 			pipe->methods = &ehci_root_ctrl_methods;
1657 			break;
1658 		case UE_DIR_IN | EHCI_INTR_ENDPT:
1659 			pipe->methods = &ehci_root_intr_methods;
1660 			break;
1661 		default:
1662 			DPRINTF(("ehci_open: bad bEndpointAddress 0x%02x\n",
1663 			    ed->bEndpointAddress));
1664 			return (USBD_INVAL);
1665 		}
1666 		return (USBD_NORMAL_COMPLETION);
1667 	}
1668 
1669 	/* XXX All this stuff is only valid for async. */
1670 	switch (dev->speed) {
1671 	case USB_SPEED_LOW:  speed = EHCI_QH_SPEED_LOW;  break;
1672 	case USB_SPEED_FULL: speed = EHCI_QH_SPEED_FULL; break;
1673 	case USB_SPEED_HIGH: speed = EHCI_QH_SPEED_HIGH; break;
1674 	default: panic("ehci_open: bad device speed %d", dev->speed);
1675 	}
1676 	if (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_ISOCHRONOUS) {
1677 		aprint_error_dev(sc->sc_dev, "error opening low/full speed "
1678 		    "isoc endpoint.\n");
1679 		aprint_normal_dev(sc->sc_dev, "a low/full speed device is "
1680 		    "attached to a USB2 hub, and transaction translations are "
1681 		    "not yet supported.\n");
1682 		aprint_normal_dev(sc->sc_dev, "reattach the device to the "
1683 		    "root hub instead.\n");
1684 		DPRINTFN(1,("ehci_open: hshubaddr=%d hshubport=%d\n",
1685 			    hshubaddr, hshubport));
1686 		return USBD_INVAL;
1687 	}
1688 
1689 	/*
1690 	 * For interrupt transfer, nak throttling must be disabled, but for
1691 	 * the other transfer type, nak throttling should be enabled from the
1692 	 * viewpoint that avoids the memory thrashing.
1693 	 */
1694 	naks = (xfertype == UE_INTERRUPT) ? 0
1695 	    : ((speed == EHCI_QH_SPEED_HIGH) ? 4 : 0);
1696 
1697 	/* Allocate sqh for everything, save isoc xfers */
1698 	if (xfertype != UE_ISOCHRONOUS) {
1699 		sqh = ehci_alloc_sqh(sc);
1700 		if (sqh == NULL)
1701 			return (USBD_NOMEM);
1702 		/* qh_link filled when the QH is added */
1703 		sqh->qh.qh_endp = htole32(
1704 		    EHCI_QH_SET_ADDR(addr) |
1705 		    EHCI_QH_SET_ENDPT(UE_GET_ADDR(ed->bEndpointAddress)) |
1706 		    EHCI_QH_SET_EPS(speed) |
1707 		    EHCI_QH_DTC |
1708 		    EHCI_QH_SET_MPL(UGETW(ed->wMaxPacketSize)) |
1709 		    (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_CONTROL ?
1710 		     EHCI_QH_CTL : 0) |
1711 		    EHCI_QH_SET_NRL(naks)
1712 		    );
1713 		sqh->qh.qh_endphub = htole32(
1714 		    EHCI_QH_SET_MULT(1) |
1715 		    EHCI_QH_SET_SMASK(xfertype == UE_INTERRUPT ? 0x02 : 0)
1716 		    );
1717 		if (speed != EHCI_QH_SPEED_HIGH)
1718 			sqh->qh.qh_endphub |= htole32(
1719 			    EHCI_QH_SET_PORT(hshubport) |
1720 			    EHCI_QH_SET_HUBA(hshubaddr) |
1721 			    EHCI_QH_SET_CMASK(0x08) /* XXX */
1722 			);
1723 		sqh->qh.qh_curqtd = EHCI_NULL;
1724 		/* Fill the overlay qTD */
1725 		sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
1726 		sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
1727 		sqh->qh.qh_qtd.qtd_status = htole32(0);
1728 
1729 		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1730 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1731 		epipe->sqh = sqh;
1732 	} else {
1733 		sqh = NULL;
1734 	} /*xfertype == UE_ISOC*/
1735 
1736 	switch (xfertype) {
1737 	case UE_CONTROL:
1738 		err = usb_allocmem(&sc->sc_bus, sizeof(usb_device_request_t),
1739 				   0, &epipe->u.ctl.reqdma);
1740 #ifdef EHCI_DEBUG
1741 		if (err)
1742 			printf("ehci_open: usb_allocmem()=%d\n", err);
1743 #endif
1744 		if (err)
1745 			goto bad;
1746 		pipe->methods = &ehci_device_ctrl_methods;
1747 		mutex_enter(&sc->sc_lock);
1748 		ehci_add_qh(sc, sqh, sc->sc_async_head);
1749 		mutex_exit(&sc->sc_lock);
1750 		break;
1751 	case UE_BULK:
1752 		pipe->methods = &ehci_device_bulk_methods;
1753 		mutex_enter(&sc->sc_lock);
1754 		ehci_add_qh(sc, sqh, sc->sc_async_head);
1755 		mutex_exit(&sc->sc_lock);
1756 		break;
1757 	case UE_INTERRUPT:
1758 		pipe->methods = &ehci_device_intr_methods;
1759 		ival = pipe->interval;
1760 		if (ival == USBD_DEFAULT_INTERVAL) {
1761 			if (speed == EHCI_QH_SPEED_HIGH) {
1762 				if (ed->bInterval > 16) {
1763 					/*
1764 					 * illegal with high-speed, but there
1765 					 * were documentation bugs in the spec,
1766 					 * so be generous
1767 					 */
1768 					ival = 256;
1769 				} else
1770 					ival = (1 << (ed->bInterval - 1)) / 8;
1771 			} else
1772 				ival = ed->bInterval;
1773 		}
1774 		err = ehci_device_setintr(sc, sqh, ival);
1775 		if (err)
1776 			goto bad;
1777 		break;
1778 	case UE_ISOCHRONOUS:
1779 		pipe->methods = &ehci_device_isoc_methods;
1780 		if (ed->bInterval == 0 || ed->bInterval > 16) {
1781 			printf("ehci: opening pipe with invalid bInterval\n");
1782 			err = USBD_INVAL;
1783 			goto bad;
1784 		}
1785 		if (UGETW(ed->wMaxPacketSize) == 0) {
1786 			printf("ehci: zero length endpoint open request\n");
1787 			err = USBD_INVAL;
1788 			goto bad;
1789 		}
1790 		epipe->u.isoc.next_frame = 0;
1791 		epipe->u.isoc.cur_xfers = 0;
1792 		break;
1793 	default:
1794 		DPRINTF(("ehci: bad xfer type %d\n", xfertype));
1795 		err = USBD_INVAL;
1796 		goto bad;
1797 	}
1798 	return (USBD_NORMAL_COMPLETION);
1799 
1800  bad:
1801 	if (sqh != NULL)
1802 		ehci_free_sqh(sc, sqh);
1803 	return (err);
1804 }
1805 
1806 /*
1807  * Add an ED to the schedule.  Called with USB lock held.
1808  */
1809 Static void
1810 ehci_add_qh(ehci_softc_t *sc, ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
1811 {
1812 
1813 	KASSERT(mutex_owned(&sc->sc_lock));
1814 
1815 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
1816 	    sizeof(head->qh.qh_link), BUS_DMASYNC_POSTWRITE);
1817 	sqh->next = head->next;
1818 	sqh->qh.qh_link = head->qh.qh_link;
1819 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
1820 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_PREWRITE);
1821 	head->next = sqh;
1822 	head->qh.qh_link = htole32(sqh->physaddr | EHCI_LINK_QH);
1823 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
1824 	    sizeof(head->qh.qh_link), BUS_DMASYNC_PREWRITE);
1825 
1826 #ifdef EHCI_DEBUG
1827 	if (ehcidebug > 5) {
1828 		printf("ehci_add_qh:\n");
1829 		ehci_dump_sqh(sqh);
1830 	}
1831 #endif
1832 }
1833 
1834 /*
1835  * Remove an ED from the schedule.  Called with USB lock held.
1836  */
1837 Static void
1838 ehci_rem_qh(ehci_softc_t *sc, ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
1839 {
1840 	ehci_soft_qh_t *p;
1841 
1842 	KASSERT(mutex_owned(&sc->sc_lock));
1843 
1844 	/* XXX */
1845 	for (p = head; p != NULL && p->next != sqh; p = p->next)
1846 		;
1847 	if (p == NULL)
1848 		panic("ehci_rem_qh: ED not found");
1849 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
1850 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_POSTWRITE);
1851 	p->next = sqh->next;
1852 	p->qh.qh_link = sqh->qh.qh_link;
1853 	usb_syncmem(&p->dma, p->offs + offsetof(ehci_qh_t, qh_link),
1854 	    sizeof(p->qh.qh_link), BUS_DMASYNC_PREWRITE);
1855 
1856 	ehci_sync_hc(sc);
1857 }
1858 
1859 Static void
1860 ehci_set_qh_qtd(ehci_soft_qh_t *sqh, ehci_soft_qtd_t *sqtd)
1861 {
1862 	int i;
1863 	u_int32_t status;
1864 
1865 	/* Save toggle bit and ping status. */
1866 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1867 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1868 	status = sqh->qh.qh_qtd.qtd_status &
1869 	    htole32(EHCI_QTD_TOGGLE_MASK |
1870 		    EHCI_QTD_SET_STATUS(EHCI_QTD_PINGSTATE));
1871 	/* Set HALTED to make hw leave it alone. */
1872 	sqh->qh.qh_qtd.qtd_status =
1873 	    htole32(EHCI_QTD_SET_STATUS(EHCI_QTD_HALTED));
1874 	usb_syncmem(&sqh->dma,
1875 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
1876 	    sizeof(sqh->qh.qh_qtd.qtd_status),
1877 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1878 	sqh->qh.qh_curqtd = 0;
1879 	sqh->qh.qh_qtd.qtd_next = htole32(sqtd->physaddr);
1880 	sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
1881 	for (i = 0; i < EHCI_QTD_NBUFFERS; i++)
1882 		sqh->qh.qh_qtd.qtd_buffer[i] = 0;
1883 	sqh->sqtd = sqtd;
1884 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1885 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1886 	/* Set !HALTED && !ACTIVE to start execution, preserve some fields */
1887 	sqh->qh.qh_qtd.qtd_status = status;
1888 	usb_syncmem(&sqh->dma,
1889 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
1890 	    sizeof(sqh->qh.qh_qtd.qtd_status),
1891 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1892 }
1893 
1894 /*
1895  * Ensure that the HC has released all references to the QH.  We do this
1896  * by asking for a Async Advance Doorbell interrupt and then we wait for
1897  * the interrupt.
1898  * To make this easier we first obtain exclusive use of the doorbell.
1899  */
1900 Static void
1901 ehci_sync_hc(ehci_softc_t *sc)
1902 {
1903 	int error;
1904 
1905 	KASSERT(mutex_owned(&sc->sc_lock));
1906 
1907 	if (sc->sc_dying) {
1908 		DPRINTFN(2,("ehci_sync_hc: dying\n"));
1909 		return;
1910 	}
1911 	DPRINTFN(2,("ehci_sync_hc: enter\n"));
1912 	/* ask for doorbell */
1913 	EOWRITE4(sc, EHCI_USBCMD, EOREAD4(sc, EHCI_USBCMD) | EHCI_CMD_IAAD);
1914 	DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
1915 		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
1916 	error = cv_timedwait(&sc->sc_doorbell, &sc->sc_lock, hz); /* bell wait */
1917 	DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
1918 		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
1919 #ifdef DIAGNOSTIC
1920 	if (error)
1921 		printf("ehci_sync_hc: cv_timedwait() = %d\n", error);
1922 #endif
1923 	DPRINTFN(2,("ehci_sync_hc: exit\n"));
1924 }
1925 
1926 Static void
1927 ehci_rem_free_itd_chain(ehci_softc_t *sc, struct ehci_xfer *exfer)
1928 {
1929 	struct ehci_soft_itd *itd, *prev;
1930 
1931 	prev = NULL;
1932 
1933 	if (exfer->itdstart == NULL || exfer->itdend == NULL)
1934 		panic("ehci isoc xfer being freed, but with no itd chain\n");
1935 
1936 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
1937 		prev = itd->u.frame_list.prev;
1938 		/* Unlink itd from hardware chain, or frame array */
1939 		if (prev == NULL) { /* We're at the table head */
1940 			sc->sc_softitds[itd->slot] = itd->u.frame_list.next;
1941 			sc->sc_flist[itd->slot] = itd->itd.itd_next;
1942 			usb_syncmem(&sc->sc_fldma,
1943 			    sizeof(ehci_link_t) * itd->slot,
1944                 	    sizeof(ehci_link_t),
1945 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1946 
1947 			if (itd->u.frame_list.next != NULL)
1948 				itd->u.frame_list.next->u.frame_list.prev = NULL;
1949 		} else {
1950 			/* XXX this part is untested... */
1951 			prev->itd.itd_next = itd->itd.itd_next;
1952 			usb_syncmem(&itd->dma,
1953 			    itd->offs + offsetof(ehci_itd_t, itd_next),
1954                 	    sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE);
1955 
1956 			prev->u.frame_list.next = itd->u.frame_list.next;
1957 			if (itd->u.frame_list.next != NULL)
1958 				itd->u.frame_list.next->u.frame_list.prev = prev;
1959 		}
1960 	}
1961 
1962 	prev = NULL;
1963 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
1964 		if (prev != NULL)
1965 			ehci_free_itd(sc, prev);
1966 		prev = itd;
1967 	}
1968 	if (prev)
1969 		ehci_free_itd(sc, prev);
1970 	exfer->itdstart = NULL;
1971 	exfer->itdend = NULL;
1972 }
1973 
1974 /***********/
1975 
1976 /*
1977  * Data structures and routines to emulate the root hub.
1978  */
1979 Static usb_device_descriptor_t ehci_devd = {
1980 	USB_DEVICE_DESCRIPTOR_SIZE,
1981 	UDESC_DEVICE,		/* type */
1982 	{0x00, 0x02},		/* USB version */
1983 	UDCLASS_HUB,		/* class */
1984 	UDSUBCLASS_HUB,		/* subclass */
1985 	UDPROTO_HSHUBSTT,	/* protocol */
1986 	64,			/* max packet */
1987 	{0},{0},{0x00,0x01},	/* device id */
1988 	1,2,0,			/* string indicies */
1989 	1			/* # of configurations */
1990 };
1991 
1992 Static const usb_device_qualifier_t ehci_odevd = {
1993 	USB_DEVICE_DESCRIPTOR_SIZE,
1994 	UDESC_DEVICE_QUALIFIER,	/* type */
1995 	{0x00, 0x02},		/* USB version */
1996 	UDCLASS_HUB,		/* class */
1997 	UDSUBCLASS_HUB,		/* subclass */
1998 	UDPROTO_FSHUB,		/* protocol */
1999 	64,			/* max packet */
2000 	1,			/* # of configurations */
2001 	0
2002 };
2003 
2004 Static const usb_config_descriptor_t ehci_confd = {
2005 	USB_CONFIG_DESCRIPTOR_SIZE,
2006 	UDESC_CONFIG,
2007 	{USB_CONFIG_DESCRIPTOR_SIZE +
2008 	 USB_INTERFACE_DESCRIPTOR_SIZE +
2009 	 USB_ENDPOINT_DESCRIPTOR_SIZE},
2010 	1,
2011 	1,
2012 	0,
2013 	UC_ATTR_MBO | UC_SELF_POWERED,
2014 	0			/* max power */
2015 };
2016 
2017 Static const usb_interface_descriptor_t ehci_ifcd = {
2018 	USB_INTERFACE_DESCRIPTOR_SIZE,
2019 	UDESC_INTERFACE,
2020 	0,
2021 	0,
2022 	1,
2023 	UICLASS_HUB,
2024 	UISUBCLASS_HUB,
2025 	UIPROTO_HSHUBSTT,
2026 	0
2027 };
2028 
2029 Static const usb_endpoint_descriptor_t ehci_endpd = {
2030 	USB_ENDPOINT_DESCRIPTOR_SIZE,
2031 	UDESC_ENDPOINT,
2032 	UE_DIR_IN | EHCI_INTR_ENDPT,
2033 	UE_INTERRUPT,
2034 	{8, 0},			/* max packet */
2035 	12
2036 };
2037 
2038 Static const usb_hub_descriptor_t ehci_hubd = {
2039 	USB_HUB_DESCRIPTOR_SIZE,
2040 	UDESC_HUB,
2041 	0,
2042 	{0,0},
2043 	0,
2044 	0,
2045 	{""},
2046 	{""},
2047 };
2048 
2049 /*
2050  * Simulate a hardware hub by handling all the necessary requests.
2051  */
2052 Static usbd_status
2053 ehci_root_ctrl_transfer(usbd_xfer_handle xfer)
2054 {
2055 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
2056 	usbd_status err;
2057 
2058 	/* Insert last in queue. */
2059 	mutex_enter(&sc->sc_lock);
2060 	err = usb_insert_transfer(xfer);
2061 	mutex_exit(&sc->sc_lock);
2062 	if (err)
2063 		return (err);
2064 
2065 	/* Pipe isn't running, start first */
2066 	return (ehci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2067 }
2068 
2069 Static usbd_status
2070 ehci_root_ctrl_start(usbd_xfer_handle xfer)
2071 {
2072 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
2073 	usb_device_request_t *req;
2074 	void *buf = NULL;
2075 	int port, i;
2076 	int len, value, index, l, totlen = 0;
2077 	usb_port_status_t ps;
2078 	usb_hub_descriptor_t hubd;
2079 	usbd_status err;
2080 	u_int32_t v;
2081 
2082 	if (sc->sc_dying)
2083 		return (USBD_IOERROR);
2084 
2085 #ifdef DIAGNOSTIC
2086 	if (!(xfer->rqflags & URQ_REQUEST))
2087 		/* XXX panic */
2088 		return (USBD_INVAL);
2089 #endif
2090 	req = &xfer->request;
2091 
2092 	DPRINTFN(4,("ehci_root_ctrl_start: type=0x%02x request=%02x\n",
2093 		    req->bmRequestType, req->bRequest));
2094 
2095 	len = UGETW(req->wLength);
2096 	value = UGETW(req->wValue);
2097 	index = UGETW(req->wIndex);
2098 
2099 	if (len != 0)
2100 		buf = KERNADDR(&xfer->dmabuf, 0);
2101 
2102 #define C(x,y) ((x) | ((y) << 8))
2103 	switch(C(req->bRequest, req->bmRequestType)) {
2104 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
2105 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
2106 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
2107 		/*
2108 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
2109 		 * for the integrated root hub.
2110 		 */
2111 		break;
2112 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
2113 		if (len > 0) {
2114 			*(u_int8_t *)buf = sc->sc_conf;
2115 			totlen = 1;
2116 		}
2117 		break;
2118 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2119 		DPRINTFN(8,("ehci_root_ctrl_start: wValue=0x%04x\n", value));
2120 		if (len == 0)
2121 			break;
2122 		switch(value >> 8) {
2123 		case UDESC_DEVICE:
2124 			if ((value & 0xff) != 0) {
2125 				err = USBD_IOERROR;
2126 				goto ret;
2127 			}
2128 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
2129 			USETW(ehci_devd.idVendor, sc->sc_id_vendor);
2130 			memcpy(buf, &ehci_devd, l);
2131 			break;
2132 		/*
2133 		 * We can't really operate at another speed, but the spec says
2134 		 * we need this descriptor.
2135 		 */
2136 		case UDESC_DEVICE_QUALIFIER:
2137 			if ((value & 0xff) != 0) {
2138 				err = USBD_IOERROR;
2139 				goto ret;
2140 			}
2141 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
2142 			memcpy(buf, &ehci_odevd, l);
2143 			break;
2144 		/*
2145 		 * We can't really operate at another speed, but the spec says
2146 		 * we need this descriptor.
2147 		 */
2148 		case UDESC_OTHER_SPEED_CONFIGURATION:
2149 		case UDESC_CONFIG:
2150 			if ((value & 0xff) != 0) {
2151 				err = USBD_IOERROR;
2152 				goto ret;
2153 			}
2154 			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
2155 			memcpy(buf, &ehci_confd, l);
2156 			((usb_config_descriptor_t *)buf)->bDescriptorType =
2157 				value >> 8;
2158 			buf = (char *)buf + l;
2159 			len -= l;
2160 			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
2161 			totlen += l;
2162 			memcpy(buf, &ehci_ifcd, l);
2163 			buf = (char *)buf + l;
2164 			len -= l;
2165 			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
2166 			totlen += l;
2167 			memcpy(buf, &ehci_endpd, l);
2168 			break;
2169 		case UDESC_STRING:
2170 #define sd ((usb_string_descriptor_t *)buf)
2171 			switch (value & 0xff) {
2172 			case 0: /* Language table */
2173 				totlen = usb_makelangtbl(sd, len);
2174 				break;
2175 			case 1: /* Vendor */
2176 				totlen = usb_makestrdesc(sd, len,
2177 							 sc->sc_vendor);
2178 				break;
2179 			case 2: /* Product */
2180 				totlen = usb_makestrdesc(sd, len,
2181 							 "EHCI root hub");
2182 				break;
2183 			}
2184 #undef sd
2185 			break;
2186 		default:
2187 			err = USBD_IOERROR;
2188 			goto ret;
2189 		}
2190 		break;
2191 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
2192 		if (len > 0) {
2193 			*(u_int8_t *)buf = 0;
2194 			totlen = 1;
2195 		}
2196 		break;
2197 	case C(UR_GET_STATUS, UT_READ_DEVICE):
2198 		if (len > 1) {
2199 			USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
2200 			totlen = 2;
2201 		}
2202 		break;
2203 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
2204 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
2205 		if (len > 1) {
2206 			USETW(((usb_status_t *)buf)->wStatus, 0);
2207 			totlen = 2;
2208 		}
2209 		break;
2210 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
2211 		if (value >= USB_MAX_DEVICES) {
2212 			err = USBD_IOERROR;
2213 			goto ret;
2214 		}
2215 		sc->sc_addr = value;
2216 		break;
2217 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
2218 		if (value != 0 && value != 1) {
2219 			err = USBD_IOERROR;
2220 			goto ret;
2221 		}
2222 		sc->sc_conf = value;
2223 		break;
2224 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
2225 		break;
2226 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
2227 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
2228 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
2229 		err = USBD_IOERROR;
2230 		goto ret;
2231 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
2232 		break;
2233 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
2234 		break;
2235 	/* Hub requests */
2236 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2237 		break;
2238 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2239 		DPRINTFN(4, ("ehci_root_ctrl_start: UR_CLEAR_PORT_FEATURE "
2240 			     "port=%d feature=%d\n",
2241 			     index, value));
2242 		if (index < 1 || index > sc->sc_noport) {
2243 			err = USBD_IOERROR;
2244 			goto ret;
2245 		}
2246 		port = EHCI_PORTSC(index);
2247 		v = EOREAD4(sc, port);
2248 		DPRINTFN(4, ("ehci_root_ctrl_start: portsc=0x%08x\n", v));
2249 		v &= ~EHCI_PS_CLEAR;
2250 		switch(value) {
2251 		case UHF_PORT_ENABLE:
2252 			EOWRITE4(sc, port, v &~ EHCI_PS_PE);
2253 			break;
2254 		case UHF_PORT_SUSPEND:
2255 			if (!(v & EHCI_PS_SUSP)) /* not suspended */
2256 				break;
2257 			v &= ~EHCI_PS_SUSP;
2258 			EOWRITE4(sc, port, v | EHCI_PS_FPR);
2259 			/* see USB2 spec ch. 7.1.7.7 */
2260 			usb_delay_ms(&sc->sc_bus, 20);
2261 			EOWRITE4(sc, port, v);
2262 			usb_delay_ms(&sc->sc_bus, 2);
2263 #ifdef DEBUG
2264 			v = EOREAD4(sc, port);
2265 			if (v & (EHCI_PS_FPR | EHCI_PS_SUSP))
2266 				printf("ehci: resume failed: %x\n", v);
2267 #endif
2268 			break;
2269 		case UHF_PORT_POWER:
2270 			if (sc->sc_hasppc)
2271 				EOWRITE4(sc, port, v &~ EHCI_PS_PP);
2272 			break;
2273 		case UHF_PORT_TEST:
2274 			DPRINTFN(2,("ehci_root_ctrl_start: clear port test "
2275 				    "%d\n", index));
2276 			break;
2277 		case UHF_PORT_INDICATOR:
2278 			DPRINTFN(2,("ehci_root_ctrl_start: clear port ind "
2279 				    "%d\n", index));
2280 			EOWRITE4(sc, port, v &~ EHCI_PS_PIC);
2281 			break;
2282 		case UHF_C_PORT_CONNECTION:
2283 			EOWRITE4(sc, port, v | EHCI_PS_CSC);
2284 			break;
2285 		case UHF_C_PORT_ENABLE:
2286 			EOWRITE4(sc, port, v | EHCI_PS_PEC);
2287 			break;
2288 		case UHF_C_PORT_SUSPEND:
2289 			/* how? */
2290 			break;
2291 		case UHF_C_PORT_OVER_CURRENT:
2292 			EOWRITE4(sc, port, v | EHCI_PS_OCC);
2293 			break;
2294 		case UHF_C_PORT_RESET:
2295 			sc->sc_isreset[index] = 0;
2296 			break;
2297 		default:
2298 			err = USBD_IOERROR;
2299 			goto ret;
2300 		}
2301 #if 0
2302 		switch(value) {
2303 		case UHF_C_PORT_CONNECTION:
2304 		case UHF_C_PORT_ENABLE:
2305 		case UHF_C_PORT_SUSPEND:
2306 		case UHF_C_PORT_OVER_CURRENT:
2307 		case UHF_C_PORT_RESET:
2308 		default:
2309 			break;
2310 		}
2311 #endif
2312 		break;
2313 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2314 		if (len == 0)
2315 			break;
2316 		if ((value & 0xff) != 0) {
2317 			err = USBD_IOERROR;
2318 			goto ret;
2319 		}
2320 		hubd = ehci_hubd;
2321 		hubd.bNbrPorts = sc->sc_noport;
2322 		v = EOREAD4(sc, EHCI_HCSPARAMS);
2323 		USETW(hubd.wHubCharacteristics,
2324 		    EHCI_HCS_PPC(v) ? UHD_PWR_INDIVIDUAL : UHD_PWR_NO_SWITCH |
2325 		    EHCI_HCS_P_INDICATOR(EREAD4(sc, EHCI_HCSPARAMS))
2326 			? UHD_PORT_IND : 0);
2327 		hubd.bPwrOn2PwrGood = 200; /* XXX can't find out? */
2328 		for (i = 0, l = sc->sc_noport; l > 0; i++, l -= 8, v >>= 8)
2329 			hubd.DeviceRemovable[i++] = 0; /* XXX can't find out? */
2330 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
2331 		l = min(len, hubd.bDescLength);
2332 		totlen = l;
2333 		memcpy(buf, &hubd, l);
2334 		break;
2335 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2336 		if (len != 4) {
2337 			err = USBD_IOERROR;
2338 			goto ret;
2339 		}
2340 		memset(buf, 0, len); /* ? XXX */
2341 		totlen = len;
2342 		break;
2343 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2344 		DPRINTFN(8,("ehci_root_ctrl_start: get port status i=%d\n",
2345 			    index));
2346 		if (index < 1 || index > sc->sc_noport) {
2347 			err = USBD_IOERROR;
2348 			goto ret;
2349 		}
2350 		if (len != 4) {
2351 			err = USBD_IOERROR;
2352 			goto ret;
2353 		}
2354 		v = EOREAD4(sc, EHCI_PORTSC(index));
2355 		DPRINTFN(8,("ehci_root_ctrl_start: port status=0x%04x\n", v));
2356 
2357 		i = UPS_HIGH_SPEED;
2358 		if (sc->sc_flags & EHCIF_ETTF) {
2359 			/*
2360 			 * If we are doing embedded transaction translation,
2361 			 * then directly attached LS/FS devices are reset by
2362 			 * the EHCI controller itself.  PSPD is encoded
2363 			 * the same way as in USBSTATUS.
2364 			 */
2365 			i = __SHIFTOUT(v, EHCI_PS_PSPD) * UPS_LOW_SPEED;
2366 		}
2367 		if (v & EHCI_PS_CS)	i |= UPS_CURRENT_CONNECT_STATUS;
2368 		if (v & EHCI_PS_PE)	i |= UPS_PORT_ENABLED;
2369 		if (v & EHCI_PS_SUSP)	i |= UPS_SUSPEND;
2370 		if (v & EHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
2371 		if (v & EHCI_PS_PR)	i |= UPS_RESET;
2372 		if (v & EHCI_PS_PP)	i |= UPS_PORT_POWER;
2373 		if (sc->sc_vendor_port_status)
2374 			i = sc->sc_vendor_port_status(sc, v, i);
2375 		USETW(ps.wPortStatus, i);
2376 		i = 0;
2377 		if (v & EHCI_PS_CSC)	i |= UPS_C_CONNECT_STATUS;
2378 		if (v & EHCI_PS_PEC)	i |= UPS_C_PORT_ENABLED;
2379 		if (v & EHCI_PS_OCC)	i |= UPS_C_OVERCURRENT_INDICATOR;
2380 		if (sc->sc_isreset[index]) i |= UPS_C_PORT_RESET;
2381 		USETW(ps.wPortChange, i);
2382 		l = min(len, sizeof ps);
2383 		memcpy(buf, &ps, l);
2384 		totlen = l;
2385 		break;
2386 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2387 		err = USBD_IOERROR;
2388 		goto ret;
2389 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2390 		break;
2391 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2392 		if (index < 1 || index > sc->sc_noport) {
2393 			err = USBD_IOERROR;
2394 			goto ret;
2395 		}
2396 		port = EHCI_PORTSC(index);
2397 		v = EOREAD4(sc, port);
2398 		DPRINTFN(4, ("ehci_root_ctrl_start: portsc=0x%08x\n", v));
2399 		v &= ~EHCI_PS_CLEAR;
2400 		switch(value) {
2401 		case UHF_PORT_ENABLE:
2402 			EOWRITE4(sc, port, v | EHCI_PS_PE);
2403 			break;
2404 		case UHF_PORT_SUSPEND:
2405 			EOWRITE4(sc, port, v | EHCI_PS_SUSP);
2406 			break;
2407 		case UHF_PORT_RESET:
2408 			DPRINTFN(5,("ehci_root_ctrl_start: reset port %d\n",
2409 				    index));
2410 			if (EHCI_PS_IS_LOWSPEED(v)
2411 			    && sc->sc_ncomp > 0
2412 			    && !(sc->sc_flags & EHCIF_ETTF)) {
2413 				/*
2414 				 * Low speed device on non-ETTF controller or
2415 				 * unaccompanied controller, give up ownership.
2416 				 */
2417 				ehci_disown(sc, index, 1);
2418 				break;
2419 			}
2420 			/* Start reset sequence. */
2421 			v &= ~ (EHCI_PS_PE | EHCI_PS_PR);
2422 			EOWRITE4(sc, port, v | EHCI_PS_PR);
2423 			/* Wait for reset to complete. */
2424 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
2425 			if (sc->sc_dying) {
2426 				err = USBD_IOERROR;
2427 				goto ret;
2428 			}
2429 			/*
2430 			 * An embedded transaction translater will automatically
2431 			 * terminate the reset sequence so there's no need to
2432 			 * it.
2433 			 */
2434 			v = EOREAD4(sc, port);
2435 			if (v & EHCI_PS_PR) {
2436 				/* Terminate reset sequence. */
2437 				EOWRITE4(sc, port, v & ~EHCI_PS_PR);
2438 				/* Wait for HC to complete reset. */
2439 				usb_delay_ms(&sc->sc_bus,
2440 				    EHCI_PORT_RESET_COMPLETE);
2441 				if (sc->sc_dying) {
2442 					err = USBD_IOERROR;
2443 					goto ret;
2444 				}
2445 			}
2446 
2447 			v = EOREAD4(sc, port);
2448 			DPRINTF(("ehci after reset, status=0x%08x\n", v));
2449 			if (v & EHCI_PS_PR) {
2450 				printf("%s: port reset timeout\n",
2451 				       device_xname(sc->sc_dev));
2452 				return (USBD_TIMEOUT);
2453 			}
2454 			if (!(v & EHCI_PS_PE)) {
2455 				/* Not a high speed device, give up ownership.*/
2456 				ehci_disown(sc, index, 0);
2457 				break;
2458 			}
2459 			sc->sc_isreset[index] = 1;
2460 			DPRINTF(("ehci port %d reset, status = 0x%08x\n",
2461 				 index, v));
2462 			break;
2463 		case UHF_PORT_POWER:
2464 			DPRINTFN(2,("ehci_root_ctrl_start: set port power "
2465 				    "%d (has PPC = %d)\n", index,
2466 				    sc->sc_hasppc));
2467 			if (sc->sc_hasppc)
2468 				EOWRITE4(sc, port, v | EHCI_PS_PP);
2469 			break;
2470 		case UHF_PORT_TEST:
2471 			DPRINTFN(2,("ehci_root_ctrl_start: set port test "
2472 				    "%d\n", index));
2473 			break;
2474 		case UHF_PORT_INDICATOR:
2475 			DPRINTFN(2,("ehci_root_ctrl_start: set port ind "
2476 				    "%d\n", index));
2477 			EOWRITE4(sc, port, v | EHCI_PS_PIC);
2478 			break;
2479 		default:
2480 			err = USBD_IOERROR;
2481 			goto ret;
2482 		}
2483 		break;
2484 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
2485 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
2486 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
2487 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
2488 		break;
2489 	default:
2490 		err = USBD_IOERROR;
2491 		goto ret;
2492 	}
2493 	xfer->actlen = totlen;
2494 	err = USBD_NORMAL_COMPLETION;
2495  ret:
2496 	mutex_enter(&sc->sc_lock);
2497 	xfer->status = err;
2498 	usb_transfer_complete(xfer);
2499 	mutex_exit(&sc->sc_lock);
2500 	return (USBD_IN_PROGRESS);
2501 }
2502 
2503 Static void
2504 ehci_disown(ehci_softc_t *sc, int index, int lowspeed)
2505 {
2506 	int port;
2507 	u_int32_t v;
2508 
2509 	DPRINTF(("ehci_disown: index=%d lowspeed=%d\n", index, lowspeed));
2510 #ifdef DIAGNOSTIC
2511 	if (sc->sc_npcomp != 0) {
2512 		int i = (index-1) / sc->sc_npcomp;
2513 		if (i >= sc->sc_ncomp)
2514 			printf("%s: strange port\n",
2515 			       device_xname(sc->sc_dev));
2516 		else
2517 			printf("%s: handing over %s speed device on "
2518 			       "port %d to %s\n",
2519 			       device_xname(sc->sc_dev),
2520 			       lowspeed ? "low" : "full",
2521 			       index, device_xname(sc->sc_comps[i]));
2522 	} else {
2523 		printf("%s: npcomp == 0\n", device_xname(sc->sc_dev));
2524 	}
2525 #endif
2526 	port = EHCI_PORTSC(index);
2527 	v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
2528 	EOWRITE4(sc, port, v | EHCI_PS_PO);
2529 }
2530 
2531 /* Abort a root control request. */
2532 Static void
2533 ehci_root_ctrl_abort(usbd_xfer_handle xfer)
2534 {
2535 	/* Nothing to do, all transfers are synchronous. */
2536 }
2537 
2538 /* Close the root pipe. */
2539 Static void
2540 ehci_root_ctrl_close(usbd_pipe_handle pipe)
2541 {
2542 	DPRINTF(("ehci_root_ctrl_close\n"));
2543 	/* Nothing to do. */
2544 }
2545 
2546 Static void
2547 ehci_root_intr_done(usbd_xfer_handle xfer)
2548 {
2549 	xfer->hcpriv = NULL;
2550 }
2551 
2552 Static usbd_status
2553 ehci_root_intr_transfer(usbd_xfer_handle xfer)
2554 {
2555 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
2556 	usbd_status err;
2557 
2558 	/* Insert last in queue. */
2559 	mutex_enter(&sc->sc_lock);
2560 	err = usb_insert_transfer(xfer);
2561 	mutex_exit(&sc->sc_lock);
2562 	if (err)
2563 		return (err);
2564 
2565 	/* Pipe isn't running, start first */
2566 	return (ehci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2567 }
2568 
2569 Static usbd_status
2570 ehci_root_intr_start(usbd_xfer_handle xfer)
2571 {
2572 	usbd_pipe_handle pipe = xfer->pipe;
2573 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2574 
2575 	if (sc->sc_dying)
2576 		return (USBD_IOERROR);
2577 
2578 	mutex_enter(&sc->sc_lock);
2579 	sc->sc_intrxfer = xfer;
2580 	mutex_exit(&sc->sc_lock);
2581 
2582 	return (USBD_IN_PROGRESS);
2583 }
2584 
2585 /* Abort a root interrupt request. */
2586 Static void
2587 ehci_root_intr_abort(usbd_xfer_handle xfer)
2588 {
2589 #ifdef DIAGNOSTIC
2590 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
2591 #endif
2592 
2593 	KASSERT(mutex_owned(&sc->sc_lock));
2594 	if (xfer->pipe->intrxfer == xfer) {
2595 		DPRINTF(("ehci_root_intr_abort: remove\n"));
2596 		xfer->pipe->intrxfer = NULL;
2597 	}
2598 	xfer->status = USBD_CANCELLED;
2599 	usb_transfer_complete(xfer);
2600 }
2601 
2602 /* Close the root pipe. */
2603 Static void
2604 ehci_root_intr_close(usbd_pipe_handle pipe)
2605 {
2606 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2607 
2608 	KASSERT(mutex_owned(&sc->sc_lock));
2609 
2610 	DPRINTF(("ehci_root_intr_close\n"));
2611 
2612 	sc->sc_intrxfer = NULL;
2613 }
2614 
2615 Static void
2616 ehci_root_ctrl_done(usbd_xfer_handle xfer)
2617 {
2618 	xfer->hcpriv = NULL;
2619 }
2620 
2621 /************************/
2622 
2623 Static ehci_soft_qh_t *
2624 ehci_alloc_sqh(ehci_softc_t *sc)
2625 {
2626 	ehci_soft_qh_t *sqh;
2627 	usbd_status err;
2628 	int i, offs;
2629 	usb_dma_t dma;
2630 
2631 	if (sc->sc_freeqhs == NULL) {
2632 		DPRINTFN(2, ("ehci_alloc_sqh: allocating chunk\n"));
2633 		err = usb_allocmem(&sc->sc_bus, EHCI_SQH_SIZE * EHCI_SQH_CHUNK,
2634 			  EHCI_PAGE_SIZE, &dma);
2635 #ifdef EHCI_DEBUG
2636 		if (err)
2637 			printf("ehci_alloc_sqh: usb_allocmem()=%d\n", err);
2638 #endif
2639 		if (err)
2640 			return (NULL);
2641 		for(i = 0; i < EHCI_SQH_CHUNK; i++) {
2642 			offs = i * EHCI_SQH_SIZE;
2643 			sqh = KERNADDR(&dma, offs);
2644 			sqh->physaddr = DMAADDR(&dma, offs);
2645 			sqh->dma = dma;
2646 			sqh->offs = offs;
2647 			sqh->next = sc->sc_freeqhs;
2648 			sc->sc_freeqhs = sqh;
2649 		}
2650 	}
2651 	sqh = sc->sc_freeqhs;
2652 	sc->sc_freeqhs = sqh->next;
2653 	memset(&sqh->qh, 0, sizeof(ehci_qh_t));
2654 	sqh->next = NULL;
2655 	return (sqh);
2656 }
2657 
2658 Static void
2659 ehci_free_sqh(ehci_softc_t *sc, ehci_soft_qh_t *sqh)
2660 {
2661 	sqh->next = sc->sc_freeqhs;
2662 	sc->sc_freeqhs = sqh;
2663 }
2664 
2665 Static ehci_soft_qtd_t *
2666 ehci_alloc_sqtd(ehci_softc_t *sc)
2667 {
2668 	ehci_soft_qtd_t *sqtd = NULL;
2669 	usbd_status err;
2670 	int i, offs;
2671 	usb_dma_t dma;
2672 
2673 	if (sc->sc_freeqtds == NULL) {
2674 		DPRINTFN(2, ("ehci_alloc_sqtd: allocating chunk\n"));
2675 
2676 		err = usb_allocmem(&sc->sc_bus, EHCI_SQTD_SIZE*EHCI_SQTD_CHUNK,
2677 			  EHCI_PAGE_SIZE, &dma);
2678 #ifdef EHCI_DEBUG
2679 		if (err)
2680 			printf("ehci_alloc_sqtd: usb_allocmem()=%d\n", err);
2681 #endif
2682 		if (err)
2683 			goto done;
2684 
2685 		for(i = 0; i < EHCI_SQTD_CHUNK; i++) {
2686 			offs = i * EHCI_SQTD_SIZE;
2687 			sqtd = KERNADDR(&dma, offs);
2688 			sqtd->physaddr = DMAADDR(&dma, offs);
2689 			sqtd->dma = dma;
2690 			sqtd->offs = offs;
2691 
2692 			sqtd->nextqtd = sc->sc_freeqtds;
2693 			sc->sc_freeqtds = sqtd;
2694 		}
2695 	}
2696 
2697 	sqtd = sc->sc_freeqtds;
2698 	sc->sc_freeqtds = sqtd->nextqtd;
2699 	memset(&sqtd->qtd, 0, sizeof(ehci_qtd_t));
2700 	sqtd->nextqtd = NULL;
2701 	sqtd->xfer = NULL;
2702 
2703 done:
2704 	return (sqtd);
2705 }
2706 
2707 Static void
2708 ehci_free_sqtd(ehci_softc_t *sc, ehci_soft_qtd_t *sqtd)
2709 {
2710 
2711 	KASSERT(mutex_owned(&sc->sc_lock));
2712 
2713 	sqtd->nextqtd = sc->sc_freeqtds;
2714 	sc->sc_freeqtds = sqtd;
2715 }
2716 
2717 Static usbd_status
2718 ehci_alloc_sqtd_chain(struct ehci_pipe *epipe, ehci_softc_t *sc,
2719 		     int alen, int rd, usbd_xfer_handle xfer,
2720 		     ehci_soft_qtd_t **sp, ehci_soft_qtd_t **ep)
2721 {
2722 	ehci_soft_qtd_t *next, *cur;
2723 	ehci_physaddr_t nextphys;
2724 	u_int32_t qtdstatus;
2725 	int len, curlen, mps;
2726 	int i, tog;
2727 	int pages, pageoffs;
2728 	bus_size_t curoffs;
2729 	vaddr_t va, va_offs;
2730 	usb_dma_t *dma = &xfer->dmabuf;
2731 	u_int16_t flags = xfer->flags;
2732 	paddr_t a;
2733 
2734 	DPRINTFN(alen<4*4096,("ehci_alloc_sqtd_chain: start len=%d\n", alen));
2735 
2736 	len = alen;
2737 	qtdstatus = EHCI_QTD_ACTIVE |
2738 	    EHCI_QTD_SET_PID(rd ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT) |
2739 	    EHCI_QTD_SET_CERR(3)
2740 	    /* IOC set below */
2741 	    /* BYTES set below */
2742 	    ;
2743 	mps = UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize);
2744 	tog = epipe->nexttoggle;
2745 	qtdstatus |= EHCI_QTD_SET_TOGGLE(tog);
2746 
2747 	cur = ehci_alloc_sqtd(sc);
2748 	*sp = cur;
2749 	if (cur == NULL)
2750 		goto nomem;
2751 
2752 	usb_syncmem(dma, 0, alen,
2753 	    rd ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
2754 	curoffs = 0;
2755 	for (;;) {
2756 		/* The EHCI hardware can handle at most 5 pages. */
2757 		va_offs = (vaddr_t)KERNADDR(dma, curoffs);
2758 		va_offs = EHCI_PAGE_OFFSET(va_offs);
2759 		if (len-curoffs < EHCI_QTD_NBUFFERS*EHCI_PAGE_SIZE - va_offs) {
2760 			/* we can handle it in this QTD */
2761 			curlen = len - curoffs;
2762 		} else {
2763 			/* must use multiple TDs, fill as much as possible. */
2764 			curlen = EHCI_QTD_NBUFFERS * EHCI_PAGE_SIZE - va_offs;
2765 
2766 			/* the length must be a multiple of the max size */
2767 			curlen -= curlen % mps;
2768 			DPRINTFN(1,("ehci_alloc_sqtd_chain: multiple QTDs, "
2769 				    "curlen=%d\n", curlen));
2770 #ifdef DIAGNOSTIC
2771 			if (curlen == 0)
2772 				panic("ehci_alloc_sqtd_chain: curlen == 0");
2773 #endif
2774 		}
2775 		DPRINTFN(4,("ehci_alloc_sqtd_chain: len=%d curlen=%d "
2776 			    "curoffs=%zu\n", len, curlen, (size_t)curoffs));
2777 
2778 		/*
2779 		 * Allocate another transfer if there's more data left,
2780 		 * or if force last short transfer flag is set and we're
2781 		 * allocating a multiple of the max packet size.
2782 		 */
2783 
2784 		if (curoffs + curlen != len ||
2785 		    ((curlen % mps) == 0 && !rd && curlen != 0 &&
2786 		     (flags & USBD_FORCE_SHORT_XFER))) {
2787 			next = ehci_alloc_sqtd(sc);
2788 			if (next == NULL)
2789 				goto nomem;
2790 			nextphys = htole32(next->physaddr);
2791 		} else {
2792 			next = NULL;
2793 			nextphys = EHCI_NULL;
2794 		}
2795 
2796 		/* Find number of pages we'll be using, insert dma addresses */
2797 		pages = EHCI_PAGE(curlen + EHCI_PAGE_SIZE -1) >> 12;
2798 		KASSERT(pages <= EHCI_QTD_NBUFFERS);
2799 		pageoffs = EHCI_PAGE(curoffs);
2800 		for (i = 0; i < pages; i++) {
2801 			a = DMAADDR(dma, pageoffs + i * EHCI_PAGE_SIZE);
2802 			cur->qtd.qtd_buffer[i] = htole32(a & 0xFFFFF000);
2803 			/* Cast up to avoid compiler warnings */
2804 			cur->qtd.qtd_buffer_hi[i] = htole32((uint64_t)a >> 32);
2805 		}
2806 
2807 		/* First buffer pointer requires a page offset to start at */
2808 		va = (vaddr_t)KERNADDR(dma, curoffs);
2809 		cur->qtd.qtd_buffer[0] |= htole32(EHCI_PAGE_OFFSET(va));
2810 
2811 		cur->nextqtd = next;
2812 		cur->qtd.qtd_next = cur->qtd.qtd_altnext = nextphys;
2813 		cur->qtd.qtd_status =
2814 		    htole32(qtdstatus | EHCI_QTD_SET_BYTES(curlen));
2815 		cur->xfer = xfer;
2816 		cur->len = curlen;
2817 
2818 		DPRINTFN(10,("ehci_alloc_sqtd_chain: cbp=0x%08zx end=0x%08zx\n",
2819 			    (size_t)curoffs, (size_t)(curoffs + curlen)));
2820 
2821 		/* adjust the toggle based on the number of packets in this
2822 		   qtd */
2823 		if (((curlen + mps - 1) / mps) & 1) {
2824 			tog ^= 1;
2825 			qtdstatus ^= EHCI_QTD_TOGGLE_MASK;
2826 		}
2827 		if (next == NULL)
2828 			break;
2829 		usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
2830 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2831 		DPRINTFN(10,("ehci_alloc_sqtd_chain: extend chain\n"));
2832 		if (len)
2833 			curoffs += curlen;
2834 		cur = next;
2835 	}
2836 	cur->qtd.qtd_status |= htole32(EHCI_QTD_IOC);
2837 	usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
2838 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2839 	*ep = cur;
2840 	epipe->nexttoggle = tog;
2841 
2842 	DPRINTFN(10,("ehci_alloc_sqtd_chain: return sqtd=%p sqtdend=%p\n",
2843 		     *sp, *ep));
2844 
2845 	return (USBD_NORMAL_COMPLETION);
2846 
2847  nomem:
2848 	/* XXX free chain */
2849 	DPRINTFN(-1,("ehci_alloc_sqtd_chain: no memory\n"));
2850 	return (USBD_NOMEM);
2851 }
2852 
2853 Static void
2854 ehci_free_sqtd_chain(ehci_softc_t *sc, ehci_soft_qtd_t *sqtd,
2855 		    ehci_soft_qtd_t *sqtdend)
2856 {
2857 	ehci_soft_qtd_t *p;
2858 	int i;
2859 
2860 	DPRINTFN(10,("ehci_free_sqtd_chain: sqtd=%p sqtdend=%p\n",
2861 		     sqtd, sqtdend));
2862 
2863 	for (i = 0; sqtd != sqtdend; sqtd = p, i++) {
2864 		p = sqtd->nextqtd;
2865 		ehci_free_sqtd(sc, sqtd);
2866 	}
2867 }
2868 
2869 Static ehci_soft_itd_t *
2870 ehci_alloc_itd(ehci_softc_t *sc)
2871 {
2872 	struct ehci_soft_itd *itd, *freeitd;
2873 	usbd_status err;
2874 	int i, offs, frindex, previndex;
2875 	usb_dma_t dma;
2876 
2877 	mutex_enter(&sc->sc_lock);
2878 
2879 	/* Find an itd that wasn't freed this frame or last frame. This can
2880 	 * discard itds that were freed before frindex wrapped around
2881 	 * XXX - can this lead to thrashing? Could fix by enabling wrap-around
2882 	 *       interrupt and fiddling with list when that happens */
2883 	frindex = (EOREAD4(sc, EHCI_FRINDEX) + 1) >> 3;
2884 	previndex = (frindex != 0) ? frindex - 1 : sc->sc_flsize;
2885 
2886 	freeitd = NULL;
2887 	LIST_FOREACH(itd, &sc->sc_freeitds, u.free_list) {
2888 		if (itd == NULL)
2889 			break;
2890 		if (itd->slot != frindex && itd->slot != previndex) {
2891 			freeitd = itd;
2892 			break;
2893 		}
2894 	}
2895 
2896 	if (freeitd == NULL) {
2897 		DPRINTFN(2, ("ehci_alloc_itd allocating chunk\n"));
2898 		err = usb_allocmem(&sc->sc_bus, EHCI_ITD_SIZE * EHCI_ITD_CHUNK,
2899 				EHCI_PAGE_SIZE, &dma);
2900 
2901 		if (err) {
2902 			DPRINTF(("ehci_alloc_itd, alloc returned %d\n", err));
2903 			mutex_exit(&sc->sc_lock);
2904 			return NULL;
2905 		}
2906 
2907 		for (i = 0; i < EHCI_ITD_CHUNK; i++) {
2908 			offs = i * EHCI_ITD_SIZE;
2909 			itd = KERNADDR(&dma, offs);
2910 			itd->physaddr = DMAADDR(&dma, offs);
2911 	 		itd->dma = dma;
2912 			itd->offs = offs;
2913 			LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
2914 		}
2915 		freeitd = LIST_FIRST(&sc->sc_freeitds);
2916 	}
2917 
2918 	itd = freeitd;
2919 	LIST_REMOVE(itd, u.free_list);
2920 	memset(&itd->itd, 0, sizeof(ehci_itd_t));
2921 	usb_syncmem(&itd->dma, itd->offs + offsetof(ehci_itd_t, itd_next),
2922                     sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE |
2923                     BUS_DMASYNC_PREREAD);
2924 
2925 	itd->u.frame_list.next = NULL;
2926 	itd->u.frame_list.prev = NULL;
2927 	itd->xfer_next = NULL;
2928 	itd->slot = 0;
2929 
2930 	mutex_exit(&sc->sc_lock);
2931 
2932 	return itd;
2933 }
2934 
2935 Static void
2936 ehci_free_itd(ehci_softc_t *sc, ehci_soft_itd_t *itd)
2937 {
2938 
2939 	KASSERT(mutex_owned(&sc->sc_lock));
2940 
2941 	LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
2942 }
2943 
2944 /****************/
2945 
2946 /*
2947  * Close a reqular pipe.
2948  * Assumes that there are no pending transactions.
2949  */
2950 Static void
2951 ehci_close_pipe(usbd_pipe_handle pipe, ehci_soft_qh_t *head)
2952 {
2953 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
2954 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2955 	ehci_soft_qh_t *sqh = epipe->sqh;
2956 
2957 	KASSERT(mutex_owned(&sc->sc_lock));
2958 
2959 	ehci_rem_qh(sc, sqh, head);
2960 	ehci_free_sqh(sc, epipe->sqh);
2961 }
2962 
2963 /*
2964  * Abort a device request.
2965  * If this routine is called at splusb() it guarantees that the request
2966  * will be removed from the hardware scheduling and that the callback
2967  * for it will be called with USBD_CANCELLED status.
2968  * It's impossible to guarantee that the requested transfer will not
2969  * have happened since the hardware runs concurrently.
2970  * If the transaction has already happened we rely on the ordinary
2971  * interrupt processing to process it.
2972  * XXX This is most probably wrong.
2973  * XXXMRG this doesn't make sense anymore.
2974  */
2975 Static void
2976 ehci_abort_xfer(usbd_xfer_handle xfer, usbd_status status)
2977 {
2978 #define exfer EXFER(xfer)
2979 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
2980 	ehci_softc_t *sc = epipe->pipe.device->bus->hci_private;
2981 	ehci_soft_qh_t *sqh = epipe->sqh;
2982 	ehci_soft_qtd_t *sqtd;
2983 	ehci_physaddr_t cur;
2984 	u_int32_t qhstatus;
2985 	int hit;
2986 	int wake;
2987 
2988 	DPRINTF(("ehci_abort_xfer: xfer=%p pipe=%p\n", xfer, epipe));
2989 
2990 	KASSERT(mutex_owned(&sc->sc_lock));
2991 
2992 	if (sc->sc_dying) {
2993 		/* If we're dying, just do the software part. */
2994 		xfer->status = status;	/* make software ignore it */
2995 		callout_stop(&xfer->timeout_handle);
2996 		usb_transfer_complete(xfer);
2997 		return;
2998 	}
2999 
3000 	if (cpu_intr_p() || cpu_softintr_p())
3001 		panic("ehci_abort_xfer: not in process context");
3002 
3003 	/*
3004 	 * If an abort is already in progress then just wait for it to
3005 	 * complete and return.
3006 	 */
3007 	if (xfer->hcflags & UXFER_ABORTING) {
3008 		DPRINTFN(2, ("ehci_abort_xfer: already aborting\n"));
3009 #ifdef DIAGNOSTIC
3010 		if (status == USBD_TIMEOUT)
3011 			printf("ehci_abort_xfer: TIMEOUT while aborting\n");
3012 #endif
3013 		/* Override the status which might be USBD_TIMEOUT. */
3014 		xfer->status = status;
3015 		DPRINTFN(2, ("ehci_abort_xfer: waiting for abort to finish\n"));
3016 		xfer->hcflags |= UXFER_ABORTWAIT;
3017 		while (xfer->hcflags & UXFER_ABORTING)
3018 			cv_wait(&xfer->hccv, &sc->sc_lock);
3019 		return;
3020 	}
3021 	xfer->hcflags |= UXFER_ABORTING;
3022 
3023 	/*
3024 	 * Step 1: Make interrupt routine and hardware ignore xfer.
3025 	 */
3026 	xfer->status = status;	/* make software ignore it */
3027 	callout_stop(&xfer->timeout_handle);
3028 
3029 	usb_syncmem(&sqh->dma,
3030 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3031 	    sizeof(sqh->qh.qh_qtd.qtd_status),
3032 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3033 	qhstatus = sqh->qh.qh_qtd.qtd_status;
3034 	sqh->qh.qh_qtd.qtd_status = qhstatus | htole32(EHCI_QTD_HALTED);
3035 	usb_syncmem(&sqh->dma,
3036 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3037 	    sizeof(sqh->qh.qh_qtd.qtd_status),
3038 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3039 	for (sqtd = exfer->sqtdstart; ; sqtd = sqtd->nextqtd) {
3040 		usb_syncmem(&sqtd->dma,
3041 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
3042 		    sizeof(sqtd->qtd.qtd_status),
3043 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3044 		sqtd->qtd.qtd_status |= htole32(EHCI_QTD_HALTED);
3045 		usb_syncmem(&sqtd->dma,
3046 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
3047 		    sizeof(sqtd->qtd.qtd_status),
3048 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3049 		if (sqtd == exfer->sqtdend)
3050 			break;
3051 	}
3052 
3053 	/*
3054 	 * Step 2: Wait until we know hardware has finished any possible
3055 	 * use of the xfer.  Also make sure the soft interrupt routine
3056 	 * has run.
3057 	 */
3058 	ehci_sync_hc(sc);
3059 	sc->sc_softwake = 1;
3060 	usb_schedsoftintr(&sc->sc_bus);
3061 	cv_wait(&sc->sc_softwake_cv, &sc->sc_lock);
3062 
3063 	/*
3064 	 * Step 3: Remove any vestiges of the xfer from the hardware.
3065 	 * The complication here is that the hardware may have executed
3066 	 * beyond the xfer we're trying to abort.  So as we're scanning
3067 	 * the TDs of this xfer we check if the hardware points to
3068 	 * any of them.
3069 	 */
3070 
3071 	usb_syncmem(&sqh->dma,
3072 	    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
3073 	    sizeof(sqh->qh.qh_curqtd),
3074 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3075 	cur = EHCI_LINK_ADDR(le32toh(sqh->qh.qh_curqtd));
3076 	hit = 0;
3077 	for (sqtd = exfer->sqtdstart; ; sqtd = sqtd->nextqtd) {
3078 		hit |= cur == sqtd->physaddr;
3079 		if (sqtd == exfer->sqtdend)
3080 			break;
3081 	}
3082 	sqtd = sqtd->nextqtd;
3083 	/* Zap curqtd register if hardware pointed inside the xfer. */
3084 	if (hit && sqtd != NULL) {
3085 		DPRINTFN(1,("ehci_abort_xfer: cur=0x%08x\n", sqtd->physaddr));
3086 		sqh->qh.qh_curqtd = htole32(sqtd->physaddr); /* unlink qTDs */
3087 		usb_syncmem(&sqh->dma,
3088 		    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
3089 		    sizeof(sqh->qh.qh_curqtd),
3090 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3091 		sqh->qh.qh_qtd.qtd_status = qhstatus;
3092 		usb_syncmem(&sqh->dma,
3093 		    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3094 		    sizeof(sqh->qh.qh_qtd.qtd_status),
3095 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3096 	} else {
3097 		DPRINTFN(1,("ehci_abort_xfer: no hit\n"));
3098 	}
3099 
3100 	/*
3101 	 * Step 4: Execute callback.
3102 	 */
3103 #ifdef DIAGNOSTIC
3104 	exfer->isdone = 1;
3105 #endif
3106 	wake = xfer->hcflags & UXFER_ABORTWAIT;
3107 	xfer->hcflags &= ~(UXFER_ABORTING | UXFER_ABORTWAIT);
3108 	usb_transfer_complete(xfer);
3109 	if (wake) {
3110 		cv_broadcast(&xfer->hccv);
3111 	}
3112 
3113 	KASSERT(mutex_owned(&sc->sc_lock));
3114 #undef exfer
3115 }
3116 
3117 Static void
3118 ehci_abort_isoc_xfer(usbd_xfer_handle xfer, usbd_status status)
3119 {
3120 	ehci_isoc_trans_t trans_status;
3121 	struct ehci_pipe *epipe;
3122 	struct ehci_xfer *exfer;
3123 	ehci_softc_t *sc;
3124 	struct ehci_soft_itd *itd;
3125 	int i, wake;
3126 
3127 	epipe = (struct ehci_pipe *) xfer->pipe;
3128 	exfer = EXFER(xfer);
3129 	sc = epipe->pipe.device->bus->hci_private;
3130 
3131 	DPRINTF(("ehci_abort_isoc_xfer: xfer %p pipe %p\n", xfer, epipe));
3132 
3133 	KASSERT(mutex_owned(&sc->sc_lock));
3134 
3135 	if (sc->sc_dying) {
3136 		xfer->status = status;
3137 		callout_stop(&xfer->timeout_handle);
3138 		usb_transfer_complete(xfer);
3139 		return;
3140 	}
3141 
3142 	if (xfer->hcflags & UXFER_ABORTING) {
3143 		DPRINTFN(2, ("ehci_abort_isoc_xfer: already aborting\n"));
3144 
3145 #ifdef DIAGNOSTIC
3146 		if (status == USBD_TIMEOUT)
3147 			printf("ehci_abort_isoc_xfer: TIMEOUT while aborting\n");
3148 #endif
3149 
3150 		xfer->status = status;
3151 		DPRINTFN(2, ("ehci_abort_isoc_xfer: waiting for abort to finish\n"));
3152 		xfer->hcflags |= UXFER_ABORTWAIT;
3153 		while (xfer->hcflags & UXFER_ABORTING)
3154 			cv_wait(&xfer->hccv, &sc->sc_lock);
3155 		goto done;
3156 	}
3157 	xfer->hcflags |= UXFER_ABORTING;
3158 
3159 	xfer->status = status;
3160 	callout_stop(&xfer->timeout_handle);
3161 
3162 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
3163 		usb_syncmem(&itd->dma,
3164 		    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3165 		    sizeof(itd->itd.itd_ctl),
3166 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3167 
3168 		for (i = 0; i < 8; i++) {
3169 			trans_status = le32toh(itd->itd.itd_ctl[i]);
3170 			trans_status &= ~EHCI_ITD_ACTIVE;
3171 			itd->itd.itd_ctl[i] = htole32(trans_status);
3172 		}
3173 
3174 		usb_syncmem(&itd->dma,
3175 		    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3176 		    sizeof(itd->itd.itd_ctl),
3177 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3178 	}
3179 
3180         sc->sc_softwake = 1;
3181         usb_schedsoftintr(&sc->sc_bus);
3182 	cv_wait(&sc->sc_softwake_cv, &sc->sc_lock);
3183 
3184 #ifdef DIAGNOSTIC
3185 	exfer->isdone = 1;
3186 #endif
3187 	wake = xfer->hcflags & UXFER_ABORTWAIT;
3188 	xfer->hcflags &= ~(UXFER_ABORTING | UXFER_ABORTWAIT);
3189 	usb_transfer_complete(xfer);
3190 	if (wake) {
3191 		cv_broadcast(&xfer->hccv);
3192 	}
3193 
3194 done:
3195 	KASSERT(mutex_owned(&sc->sc_lock));
3196 	return;
3197 }
3198 
3199 Static void
3200 ehci_timeout(void *addr)
3201 {
3202 	struct ehci_xfer *exfer = addr;
3203 	struct ehci_pipe *epipe = (struct ehci_pipe *)exfer->xfer.pipe;
3204 	ehci_softc_t *sc = epipe->pipe.device->bus->hci_private;
3205 
3206 	DPRINTF(("ehci_timeout: exfer=%p\n", exfer));
3207 #ifdef EHCI_DEBUG
3208 	if (ehcidebug > 1)
3209 		usbd_dump_pipe(exfer->xfer.pipe);
3210 #endif
3211 
3212 	if (sc->sc_dying) {
3213 		mutex_enter(&sc->sc_lock);
3214 		ehci_abort_xfer(&exfer->xfer, USBD_TIMEOUT);
3215 		mutex_exit(&sc->sc_lock);
3216 		return;
3217 	}
3218 
3219 	/* Execute the abort in a process context. */
3220 	usb_init_task(&exfer->abort_task, ehci_timeout_task, addr,
3221 	    USB_TASKQ_MPSAFE);
3222 	usb_add_task(exfer->xfer.pipe->device, &exfer->abort_task,
3223 	    USB_TASKQ_HC);
3224 }
3225 
3226 Static void
3227 ehci_timeout_task(void *addr)
3228 {
3229 	usbd_xfer_handle xfer = addr;
3230 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3231 
3232 	DPRINTF(("ehci_timeout_task: xfer=%p\n", xfer));
3233 
3234 	mutex_enter(&sc->sc_lock);
3235 	ehci_abort_xfer(xfer, USBD_TIMEOUT);
3236 	mutex_exit(&sc->sc_lock);
3237 }
3238 
3239 /************************/
3240 
3241 Static usbd_status
3242 ehci_device_ctrl_transfer(usbd_xfer_handle xfer)
3243 {
3244 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3245 	usbd_status err;
3246 
3247 	/* Insert last in queue. */
3248 	mutex_enter(&sc->sc_lock);
3249 	err = usb_insert_transfer(xfer);
3250 	mutex_exit(&sc->sc_lock);
3251 	if (err)
3252 		return (err);
3253 
3254 	/* Pipe isn't running, start first */
3255 	return (ehci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3256 }
3257 
3258 Static usbd_status
3259 ehci_device_ctrl_start(usbd_xfer_handle xfer)
3260 {
3261 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3262 	usbd_status err;
3263 
3264 	if (sc->sc_dying)
3265 		return (USBD_IOERROR);
3266 
3267 #ifdef DIAGNOSTIC
3268 	if (!(xfer->rqflags & URQ_REQUEST)) {
3269 		/* XXX panic */
3270 		printf("ehci_device_ctrl_transfer: not a request\n");
3271 		return (USBD_INVAL);
3272 	}
3273 #endif
3274 
3275 	err = ehci_device_request(xfer);
3276 	if (err) {
3277 		return (err);
3278 	}
3279 
3280 	if (sc->sc_bus.use_polling)
3281 		ehci_waitintr(sc, xfer);
3282 
3283 	return (USBD_IN_PROGRESS);
3284 }
3285 
3286 Static void
3287 ehci_device_ctrl_done(usbd_xfer_handle xfer)
3288 {
3289 	struct ehci_xfer *ex = EXFER(xfer);
3290 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3291 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3292 	usb_device_request_t *req = &xfer->request;
3293 	int len = UGETW(req->wLength);
3294 	int rd = req->bmRequestType & UT_READ;
3295 
3296 	DPRINTFN(10,("ehci_ctrl_done: xfer=%p\n", xfer));
3297 
3298 	KASSERT(mutex_owned(&sc->sc_lock));
3299 
3300 #ifdef DIAGNOSTIC
3301 	if (!(xfer->rqflags & URQ_REQUEST)) {
3302 		panic("ehci_ctrl_done: not a request");
3303 	}
3304 #endif
3305 
3306 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3307 		ehci_del_intr_list(sc, ex);	/* remove from active list */
3308 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3309 		usb_syncmem(&epipe->u.ctl.reqdma, 0, sizeof *req,
3310 		    BUS_DMASYNC_POSTWRITE);
3311 		if (len)
3312 			usb_syncmem(&xfer->dmabuf, 0, len,
3313 			    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3314 	}
3315 
3316 	DPRINTFN(5, ("ehci_ctrl_done: length=%d\n", xfer->actlen));
3317 }
3318 
3319 /* Abort a device control request. */
3320 Static void
3321 ehci_device_ctrl_abort(usbd_xfer_handle xfer)
3322 {
3323 	DPRINTF(("ehci_device_ctrl_abort: xfer=%p\n", xfer));
3324 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3325 }
3326 
3327 /* Close a device control pipe. */
3328 Static void
3329 ehci_device_ctrl_close(usbd_pipe_handle pipe)
3330 {
3331 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3332 	/*struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;*/
3333 
3334 	KASSERT(mutex_owned(&sc->sc_lock));
3335 
3336 	DPRINTF(("ehci_device_ctrl_close: pipe=%p\n", pipe));
3337 
3338 	ehci_close_pipe(pipe, sc->sc_async_head);
3339 }
3340 
3341 Static usbd_status
3342 ehci_device_request(usbd_xfer_handle xfer)
3343 {
3344 #define exfer EXFER(xfer)
3345 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3346 	usb_device_request_t *req = &xfer->request;
3347 	usbd_device_handle dev = epipe->pipe.device;
3348 	ehci_softc_t *sc = dev->bus->hci_private;
3349 	int addr = dev->address;
3350 	ehci_soft_qtd_t *setup, *stat, *next;
3351 	ehci_soft_qh_t *sqh;
3352 	int isread;
3353 	int len;
3354 	usbd_status err;
3355 
3356 	isread = req->bmRequestType & UT_READ;
3357 	len = UGETW(req->wLength);
3358 
3359 	DPRINTFN(3,("ehci_device_request: type=0x%02x, request=0x%02x, "
3360 		    "wValue=0x%04x, wIndex=0x%04x len=%d, addr=%d, endpt=%d\n",
3361 		    req->bmRequestType, req->bRequest, UGETW(req->wValue),
3362 		    UGETW(req->wIndex), len, addr,
3363 		    epipe->pipe.endpoint->edesc->bEndpointAddress));
3364 
3365 	setup = ehci_alloc_sqtd(sc);
3366 	if (setup == NULL) {
3367 		err = USBD_NOMEM;
3368 		goto bad1;
3369 	}
3370 	stat = ehci_alloc_sqtd(sc);
3371 	if (stat == NULL) {
3372 		err = USBD_NOMEM;
3373 		goto bad2;
3374 	}
3375 
3376 	mutex_enter(&sc->sc_lock);
3377 
3378 	sqh = epipe->sqh;
3379 
3380 	/*
3381 	 * Update device address and length since they may have changed
3382 	 * during the setup of the control pipe in usbd_new_device().
3383 	 */
3384 	/* XXX This only needs to be done once, but it's too early in open. */
3385 	/* XXXX Should not touch ED here! */
3386 	sqh->qh.qh_endp =
3387 	    (sqh->qh.qh_endp & htole32(~(EHCI_QH_ADDRMASK | EHCI_QH_MPLMASK))) |
3388 	    htole32(
3389 	     EHCI_QH_SET_ADDR(addr) |
3390 	     EHCI_QH_SET_MPL(UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize))
3391 	    );
3392 
3393 	/* Set up data transaction */
3394 	if (len != 0) {
3395 		ehci_soft_qtd_t *end;
3396 
3397 		/* Start toggle at 1. */
3398 		epipe->nexttoggle = 1;
3399 		err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer,
3400 			  &next, &end);
3401 		if (err)
3402 			goto bad3;
3403 		end->qtd.qtd_status &= htole32(~EHCI_QTD_IOC);
3404 		end->nextqtd = stat;
3405 		end->qtd.qtd_next =
3406 		end->qtd.qtd_altnext = htole32(stat->physaddr);
3407 		usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
3408 		   BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3409 	} else {
3410 		next = stat;
3411 	}
3412 
3413 	memcpy(KERNADDR(&epipe->u.ctl.reqdma, 0), req, sizeof *req);
3414 	usb_syncmem(&epipe->u.ctl.reqdma, 0, sizeof *req, BUS_DMASYNC_PREWRITE);
3415 
3416 	/* Clear toggle */
3417 	setup->qtd.qtd_status = htole32(
3418 	    EHCI_QTD_ACTIVE |
3419 	    EHCI_QTD_SET_PID(EHCI_QTD_PID_SETUP) |
3420 	    EHCI_QTD_SET_CERR(3) |
3421 	    EHCI_QTD_SET_TOGGLE(0) |
3422 	    EHCI_QTD_SET_BYTES(sizeof *req)
3423 	    );
3424 	setup->qtd.qtd_buffer[0] = htole32(DMAADDR(&epipe->u.ctl.reqdma, 0));
3425 	setup->qtd.qtd_buffer_hi[0] = 0;
3426 	setup->nextqtd = next;
3427 	setup->qtd.qtd_next = setup->qtd.qtd_altnext = htole32(next->physaddr);
3428 	setup->xfer = xfer;
3429 	setup->len = sizeof *req;
3430 	usb_syncmem(&setup->dma, setup->offs, sizeof(setup->qtd),
3431 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3432 
3433 	stat->qtd.qtd_status = htole32(
3434 	    EHCI_QTD_ACTIVE |
3435 	    EHCI_QTD_SET_PID(isread ? EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN) |
3436 	    EHCI_QTD_SET_CERR(3) |
3437 	    EHCI_QTD_SET_TOGGLE(1) |
3438 	    EHCI_QTD_IOC
3439 	    );
3440 	stat->qtd.qtd_buffer[0] = 0; /* XXX not needed? */
3441 	stat->qtd.qtd_buffer_hi[0] = 0; /* XXX not needed? */
3442 	stat->nextqtd = NULL;
3443 	stat->qtd.qtd_next = stat->qtd.qtd_altnext = EHCI_NULL;
3444 	stat->xfer = xfer;
3445 	stat->len = 0;
3446 	usb_syncmem(&stat->dma, stat->offs, sizeof(stat->qtd),
3447 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3448 
3449 #ifdef EHCI_DEBUG
3450 	if (ehcidebug > 5) {
3451 		DPRINTF(("ehci_device_request:\n"));
3452 		ehci_dump_sqh(sqh);
3453 		ehci_dump_sqtds(setup);
3454 	}
3455 #endif
3456 
3457 	exfer->sqtdstart = setup;
3458 	exfer->sqtdend = stat;
3459 #ifdef DIAGNOSTIC
3460 	if (!exfer->isdone) {
3461 		printf("ehci_device_request: not done, exfer=%p\n", exfer);
3462 	}
3463 	exfer->isdone = 0;
3464 #endif
3465 
3466 	/* Insert qTD in QH list. */
3467 	ehci_set_qh_qtd(sqh, setup); /* also does usb_syncmem(sqh) */
3468 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3469 		callout_reset(&xfer->timeout_handle, mstohz(xfer->timeout),
3470 		    ehci_timeout, xfer);
3471 	}
3472 	ehci_add_intr_list(sc, exfer);
3473 	xfer->status = USBD_IN_PROGRESS;
3474 	mutex_exit(&sc->sc_lock);
3475 
3476 #ifdef EHCI_DEBUG
3477 	if (ehcidebug > 10) {
3478 		DPRINTF(("ehci_device_request: status=%x\n",
3479 			 EOREAD4(sc, EHCI_USBSTS)));
3480 		delay(10000);
3481 		ehci_dump_regs(sc);
3482 		ehci_dump_sqh(sc->sc_async_head);
3483 		ehci_dump_sqh(sqh);
3484 		ehci_dump_sqtds(setup);
3485 	}
3486 #endif
3487 
3488 	return (USBD_NORMAL_COMPLETION);
3489 
3490  bad3:
3491 	mutex_exit(&sc->sc_lock);
3492 	ehci_free_sqtd(sc, stat);
3493  bad2:
3494 	ehci_free_sqtd(sc, setup);
3495  bad1:
3496 	DPRINTFN(-1,("ehci_device_request: no memory\n"));
3497 	mutex_enter(&sc->sc_lock);
3498 	xfer->status = err;
3499 	usb_transfer_complete(xfer);
3500 	mutex_exit(&sc->sc_lock);
3501 	return (err);
3502 #undef exfer
3503 }
3504 
3505 /*
3506  * Some EHCI chips from VIA seem to trigger interrupts before writing back the
3507  * qTD status, or miss signalling occasionally under heavy load.  If the host
3508  * machine is too fast, we we can miss transaction completion - when we scan
3509  * the active list the transaction still seems to be active.  This generally
3510  * exhibits itself as a umass stall that never recovers.
3511  *
3512  * We work around this behaviour by setting up this callback after any softintr
3513  * that completes with transactions still pending, giving us another chance to
3514  * check for completion after the writeback has taken place.
3515  */
3516 Static void
3517 ehci_intrlist_timeout(void *arg)
3518 {
3519 	ehci_softc_t *sc = arg;
3520 
3521 	DPRINTF(("ehci_intrlist_timeout\n"));
3522 	usb_schedsoftintr(&sc->sc_bus);
3523 }
3524 
3525 /************************/
3526 
3527 Static usbd_status
3528 ehci_device_bulk_transfer(usbd_xfer_handle xfer)
3529 {
3530 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3531 	usbd_status err;
3532 
3533 	/* Insert last in queue. */
3534 	mutex_enter(&sc->sc_lock);
3535 	err = usb_insert_transfer(xfer);
3536 	mutex_exit(&sc->sc_lock);
3537 	if (err)
3538 		return (err);
3539 
3540 	/* Pipe isn't running, start first */
3541 	return (ehci_device_bulk_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3542 }
3543 
3544 Static usbd_status
3545 ehci_device_bulk_start(usbd_xfer_handle xfer)
3546 {
3547 #define exfer EXFER(xfer)
3548 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3549 	usbd_device_handle dev = epipe->pipe.device;
3550 	ehci_softc_t *sc = dev->bus->hci_private;
3551 	ehci_soft_qtd_t *data, *dataend;
3552 	ehci_soft_qh_t *sqh;
3553 	usbd_status err;
3554 	int len, isread, endpt;
3555 
3556 	DPRINTFN(2, ("ehci_device_bulk_start: xfer=%p len=%d flags=%d\n",
3557 		     xfer, xfer->length, xfer->flags));
3558 
3559 	if (sc->sc_dying)
3560 		return (USBD_IOERROR);
3561 
3562 #ifdef DIAGNOSTIC
3563 	if (xfer->rqflags & URQ_REQUEST)
3564 		panic("ehci_device_bulk_start: a request");
3565 #endif
3566 
3567 	mutex_enter(&sc->sc_lock);
3568 
3569 	len = xfer->length;
3570 	endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3571 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3572 	sqh = epipe->sqh;
3573 
3574 	epipe->u.bulk.length = len;
3575 
3576 	err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer, &data,
3577 				   &dataend);
3578 	if (err) {
3579 		DPRINTFN(-1,("ehci_device_bulk_transfer: no memory\n"));
3580 		xfer->status = err;
3581 		usb_transfer_complete(xfer);
3582 		mutex_exit(&sc->sc_lock);
3583 		return (err);
3584 	}
3585 
3586 #ifdef EHCI_DEBUG
3587 	if (ehcidebug > 5) {
3588 		DPRINTF(("ehci_device_bulk_start: data(1)\n"));
3589 		ehci_dump_sqh(sqh);
3590 		ehci_dump_sqtds(data);
3591 	}
3592 #endif
3593 
3594 	/* Set up interrupt info. */
3595 	exfer->sqtdstart = data;
3596 	exfer->sqtdend = dataend;
3597 #ifdef DIAGNOSTIC
3598 	if (!exfer->isdone) {
3599 		printf("ehci_device_bulk_start: not done, ex=%p\n", exfer);
3600 	}
3601 	exfer->isdone = 0;
3602 #endif
3603 
3604 	ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3605 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3606 		callout_reset(&xfer->timeout_handle, mstohz(xfer->timeout),
3607 		    ehci_timeout, xfer);
3608 	}
3609 	ehci_add_intr_list(sc, exfer);
3610 	xfer->status = USBD_IN_PROGRESS;
3611 	mutex_exit(&sc->sc_lock);
3612 
3613 #ifdef EHCI_DEBUG
3614 	if (ehcidebug > 10) {
3615 		DPRINTF(("ehci_device_bulk_start: data(2)\n"));
3616 		delay(10000);
3617 		DPRINTF(("ehci_device_bulk_start: data(3)\n"));
3618 		ehci_dump_regs(sc);
3619 #if 0
3620 		printf("async_head:\n");
3621 		ehci_dump_sqh(sc->sc_async_head);
3622 #endif
3623 		printf("sqh:\n");
3624 		ehci_dump_sqh(sqh);
3625 		ehci_dump_sqtds(data);
3626 	}
3627 #endif
3628 
3629 	if (sc->sc_bus.use_polling)
3630 		ehci_waitintr(sc, xfer);
3631 
3632 	return (USBD_IN_PROGRESS);
3633 #undef exfer
3634 }
3635 
3636 Static void
3637 ehci_device_bulk_abort(usbd_xfer_handle xfer)
3638 {
3639 	DPRINTF(("ehci_device_bulk_abort: xfer=%p\n", xfer));
3640 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3641 }
3642 
3643 /*
3644  * Close a device bulk pipe.
3645  */
3646 Static void
3647 ehci_device_bulk_close(usbd_pipe_handle pipe)
3648 {
3649 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3650 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
3651 
3652 	KASSERT(mutex_owned(&sc->sc_lock));
3653 
3654 	DPRINTF(("ehci_device_bulk_close: pipe=%p\n", pipe));
3655 	pipe->endpoint->datatoggle = epipe->nexttoggle;
3656 	ehci_close_pipe(pipe, sc->sc_async_head);
3657 }
3658 
3659 Static void
3660 ehci_device_bulk_done(usbd_xfer_handle xfer)
3661 {
3662 	struct ehci_xfer *ex = EXFER(xfer);
3663 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3664 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3665 	int endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3666 	int rd = UE_GET_DIR(endpt) == UE_DIR_IN;
3667 
3668 	DPRINTFN(10,("ehci_bulk_done: xfer=%p, actlen=%d\n",
3669 		     xfer, xfer->actlen));
3670 
3671 	KASSERT(mutex_owned(&sc->sc_lock));
3672 
3673 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3674 		ehci_del_intr_list(sc, ex);	/* remove from active list */
3675 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3676 		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
3677 		    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3678 	}
3679 
3680 	DPRINTFN(5, ("ehci_bulk_done: length=%d\n", xfer->actlen));
3681 }
3682 
3683 /************************/
3684 
3685 Static usbd_status
3686 ehci_device_setintr(ehci_softc_t *sc, ehci_soft_qh_t *sqh, int ival)
3687 {
3688 	struct ehci_soft_islot *isp;
3689 	int islot, lev;
3690 
3691 	/* Find a poll rate that is large enough. */
3692 	for (lev = EHCI_IPOLLRATES - 1; lev > 0; lev--)
3693 		if (EHCI_ILEV_IVAL(lev) <= ival)
3694 			break;
3695 
3696 	/* Pick an interrupt slot at the right level. */
3697 	/* XXX could do better than picking at random */
3698 	sc->sc_rand = (sc->sc_rand + 191) % sc->sc_flsize;
3699 	islot = EHCI_IQHIDX(lev, sc->sc_rand);
3700 
3701 	sqh->islot = islot;
3702 	isp = &sc->sc_islots[islot];
3703 	mutex_enter(&sc->sc_lock);
3704 	ehci_add_qh(sc, sqh, isp->sqh);
3705 	mutex_exit(&sc->sc_lock);
3706 
3707 	return (USBD_NORMAL_COMPLETION);
3708 }
3709 
3710 Static usbd_status
3711 ehci_device_intr_transfer(usbd_xfer_handle xfer)
3712 {
3713 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3714 	usbd_status err;
3715 
3716 	/* Insert last in queue. */
3717 	mutex_enter(&sc->sc_lock);
3718 	err = usb_insert_transfer(xfer);
3719 	mutex_exit(&sc->sc_lock);
3720 	if (err)
3721 		return (err);
3722 
3723 	/*
3724 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
3725 	 * so start it first.
3726 	 */
3727 	return (ehci_device_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3728 }
3729 
3730 Static usbd_status
3731 ehci_device_intr_start(usbd_xfer_handle xfer)
3732 {
3733 #define exfer EXFER(xfer)
3734 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3735 	usbd_device_handle dev = xfer->pipe->device;
3736 	ehci_softc_t *sc = dev->bus->hci_private;
3737 	ehci_soft_qtd_t *data, *dataend;
3738 	ehci_soft_qh_t *sqh;
3739 	usbd_status err;
3740 	int len, isread, endpt;
3741 
3742 	DPRINTFN(2, ("ehci_device_intr_start: xfer=%p len=%d flags=%d\n",
3743 	    xfer, xfer->length, xfer->flags));
3744 
3745 	if (sc->sc_dying)
3746 		return (USBD_IOERROR);
3747 
3748 #ifdef DIAGNOSTIC
3749 	if (xfer->rqflags & URQ_REQUEST)
3750 		panic("ehci_device_intr_start: a request");
3751 #endif
3752 
3753 	mutex_enter(&sc->sc_lock);
3754 
3755 	len = xfer->length;
3756 	endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3757 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3758 	sqh = epipe->sqh;
3759 
3760 	epipe->u.intr.length = len;
3761 
3762 	err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer, &data,
3763 	    &dataend);
3764 	if (err) {
3765 		DPRINTFN(-1, ("ehci_device_intr_start: no memory\n"));
3766 		xfer->status = err;
3767 		usb_transfer_complete(xfer);
3768 		mutex_exit(&sc->sc_lock);
3769 		return (err);
3770 	}
3771 
3772 #ifdef EHCI_DEBUG
3773 	if (ehcidebug > 5) {
3774 		DPRINTF(("ehci_device_intr_start: data(1)\n"));
3775 		ehci_dump_sqh(sqh);
3776 		ehci_dump_sqtds(data);
3777 	}
3778 #endif
3779 
3780 	/* Set up interrupt info. */
3781 	exfer->sqtdstart = data;
3782 	exfer->sqtdend = dataend;
3783 #ifdef DIAGNOSTIC
3784 	if (!exfer->isdone) {
3785 		printf("ehci_device_intr_start: not done, ex=%p\n", exfer);
3786 	}
3787 	exfer->isdone = 0;
3788 #endif
3789 
3790 	ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3791 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3792 		callout_reset(&xfer->timeout_handle, mstohz(xfer->timeout),
3793 		    ehci_timeout, xfer);
3794 	}
3795 	ehci_add_intr_list(sc, exfer);
3796 	xfer->status = USBD_IN_PROGRESS;
3797 	mutex_exit(&sc->sc_lock);
3798 
3799 #ifdef EHCI_DEBUG
3800 	if (ehcidebug > 10) {
3801 		DPRINTF(("ehci_device_intr_start: data(2)\n"));
3802 		delay(10000);
3803 		DPRINTF(("ehci_device_intr_start: data(3)\n"));
3804 		ehci_dump_regs(sc);
3805 		printf("sqh:\n");
3806 		ehci_dump_sqh(sqh);
3807 		ehci_dump_sqtds(data);
3808 	}
3809 #endif
3810 
3811 	if (sc->sc_bus.use_polling)
3812 		ehci_waitintr(sc, xfer);
3813 
3814 	return (USBD_IN_PROGRESS);
3815 #undef exfer
3816 }
3817 
3818 Static void
3819 ehci_device_intr_abort(usbd_xfer_handle xfer)
3820 {
3821 	DPRINTFN(1, ("ehci_device_intr_abort: xfer=%p\n", xfer));
3822 	if (xfer->pipe->intrxfer == xfer) {
3823 		DPRINTFN(1, ("echi_device_intr_abort: remove\n"));
3824 		xfer->pipe->intrxfer = NULL;
3825 	}
3826 	/*
3827 	 * XXX - abort_xfer uses ehci_sync_hc, which syncs via the advance
3828 	 *       async doorbell. That's dependent on the async list, wheras
3829 	 *       intr xfers are periodic, should not use this?
3830 	 */
3831 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3832 }
3833 
3834 Static void
3835 ehci_device_intr_close(usbd_pipe_handle pipe)
3836 {
3837 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3838 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
3839 	struct ehci_soft_islot *isp;
3840 
3841 	KASSERT(mutex_owned(&sc->sc_lock));
3842 
3843 	isp = &sc->sc_islots[epipe->sqh->islot];
3844 	ehci_close_pipe(pipe, isp->sqh);
3845 }
3846 
3847 Static void
3848 ehci_device_intr_done(usbd_xfer_handle xfer)
3849 {
3850 #define exfer EXFER(xfer)
3851 	struct ehci_xfer *ex = EXFER(xfer);
3852 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3853 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3854 	ehci_soft_qtd_t *data, *dataend;
3855 	ehci_soft_qh_t *sqh;
3856 	usbd_status err;
3857 	int len, isread, endpt;
3858 
3859 	DPRINTFN(10, ("ehci_device_intr_done: xfer=%p, actlen=%d\n",
3860 	    xfer, xfer->actlen));
3861 
3862 	KASSERT(mutex_owned(&sc->sc_lock));
3863 
3864 	if (xfer->pipe->repeat) {
3865 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3866 
3867 		len = epipe->u.intr.length;
3868 		xfer->length = len;
3869 		endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3870 		isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3871 		usb_syncmem(&xfer->dmabuf, 0, len,
3872 		    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3873 		sqh = epipe->sqh;
3874 
3875 		err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer,
3876 		    &data, &dataend);
3877 		if (err) {
3878 			DPRINTFN(-1, ("ehci_device_intr_done: no memory\n"));
3879 			xfer->status = err;
3880 			return;
3881 		}
3882 
3883 		/* Set up interrupt info. */
3884 		exfer->sqtdstart = data;
3885 		exfer->sqtdend = dataend;
3886 #ifdef DIAGNOSTIC
3887 		if (!exfer->isdone) {
3888 			printf("ehci_device_intr_done: not done, ex=%p\n",
3889 			    exfer);
3890 		}
3891 		exfer->isdone = 0;
3892 #endif
3893 
3894 		ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3895 		if (xfer->timeout && !sc->sc_bus.use_polling) {
3896 			callout_reset(&xfer->timeout_handle,
3897 			    mstohz(xfer->timeout), ehci_timeout, xfer);
3898 		}
3899 
3900 		xfer->status = USBD_IN_PROGRESS;
3901 	} else if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3902 		ehci_del_intr_list(sc, ex); /* remove from active list */
3903 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3904 		endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3905 		isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3906 		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
3907 		    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3908 	}
3909 #undef exfer
3910 }
3911 
3912 /************************/
3913 
3914 Static usbd_status
3915 ehci_device_isoc_transfer(usbd_xfer_handle xfer)
3916 {
3917 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3918 	usbd_status err;
3919 
3920 	mutex_enter(&sc->sc_lock);
3921 	err = usb_insert_transfer(xfer);
3922 	mutex_exit(&sc->sc_lock);
3923 	if (err && err != USBD_IN_PROGRESS)
3924 		return err;
3925 
3926 	return ehci_device_isoc_start(xfer);
3927 }
3928 
3929 Static usbd_status
3930 ehci_device_isoc_start(usbd_xfer_handle xfer)
3931 {
3932 	struct ehci_pipe *epipe;
3933 	usbd_device_handle dev;
3934 	ehci_softc_t *sc;
3935 	struct ehci_xfer *exfer;
3936 	ehci_soft_itd_t *itd, *prev, *start, *stop;
3937 	usb_dma_t *dma_buf;
3938 	int i, j, k, frames, uframes, ufrperframe;
3939 	int trans_count, offs, total_length;
3940 	int frindex;
3941 
3942 	start = NULL;
3943 	prev = NULL;
3944 	itd = NULL;
3945 	trans_count = 0;
3946 	total_length = 0;
3947 	exfer = (struct ehci_xfer *) xfer;
3948 	sc = xfer->pipe->device->bus->hci_private;
3949 	dev = xfer->pipe->device;
3950 	epipe = (struct ehci_pipe *)xfer->pipe;
3951 
3952 	/*
3953 	 * To allow continuous transfers, above we start all transfers
3954 	 * immediately. However, we're still going to get usbd_start_next call
3955 	 * this when another xfer completes. So, check if this is already
3956 	 * in progress or not
3957 	 */
3958 
3959 	if (exfer->itdstart != NULL)
3960 		return USBD_IN_PROGRESS;
3961 
3962 	DPRINTFN(2, ("ehci_device_isoc_start: xfer %p len %d flags %d\n",
3963 			xfer, xfer->length, xfer->flags));
3964 
3965 	if (sc->sc_dying)
3966 		return USBD_IOERROR;
3967 
3968 	/*
3969 	 * To avoid complication, don't allow a request right now that'll span
3970 	 * the entire frame table. To within 4 frames, to allow some leeway
3971 	 * on either side of where the hc currently is.
3972 	 */
3973 	if ((1 << (epipe->pipe.endpoint->edesc->bInterval)) *
3974 			xfer->nframes >= (sc->sc_flsize - 4) * 8) {
3975 		printf("ehci: isoc descriptor requested that spans the entire frametable, too many frames\n");
3976 		return USBD_INVAL;
3977 	}
3978 
3979 #ifdef DIAGNOSTIC
3980 	if (xfer->rqflags & URQ_REQUEST)
3981 		panic("ehci_device_isoc_start: request\n");
3982 
3983 	if (!exfer->isdone)
3984 		printf("ehci_device_isoc_start: not done, ex = %p\n", exfer);
3985 	exfer->isdone = 0;
3986 #endif
3987 
3988 	/*
3989 	 * Step 1: Allocate and initialize itds, how many do we need?
3990 	 * One per transfer if interval >= 8 microframes, fewer if we use
3991 	 * multiple microframes per frame.
3992 	 */
3993 
3994 	i = epipe->pipe.endpoint->edesc->bInterval;
3995 	if (i > 16 || i == 0) {
3996 		/* Spec page 271 says intervals > 16 are invalid */
3997 		DPRINTF(("ehci_device_isoc_start: bInvertal %d invalid\n", i));
3998 		return USBD_INVAL;
3999 	}
4000 
4001 	ufrperframe = max(1, USB_UFRAMES_PER_FRAME / (1 << (i - 1)));
4002 	frames = (xfer->nframes + (ufrperframe - 1)) / ufrperframe;
4003 	uframes = USB_UFRAMES_PER_FRAME / ufrperframe;
4004 
4005 	if (frames == 0) {
4006 		DPRINTF(("ehci_device_isoc_start: frames == 0\n"));
4007 		return USBD_INVAL;
4008 	}
4009 
4010 	dma_buf = &xfer->dmabuf;
4011 	offs = 0;
4012 
4013 	for (i = 0; i < frames; i++) {
4014 		int froffs = offs;
4015 		itd = ehci_alloc_itd(sc);
4016 
4017 		if (prev != NULL) {
4018 			prev->itd.itd_next =
4019 			    htole32(itd->physaddr | EHCI_LINK_ITD);
4020 			usb_syncmem(&itd->dma,
4021 			    itd->offs + offsetof(ehci_itd_t, itd_next),
4022                 	    sizeof(itd->itd.itd_next), BUS_DMASYNC_POSTWRITE);
4023 
4024 			prev->xfer_next = itd;
4025 	    	} else {
4026 			start = itd;
4027 		}
4028 
4029 		/*
4030 		 * Step 1.5, initialize uframes
4031 		 */
4032 		for (j = 0; j < EHCI_ITD_NUFRAMES; j += uframes) {
4033 			/* Calculate which page in the list this starts in */
4034 			int addr = DMAADDR(dma_buf, froffs);
4035 			addr = EHCI_PAGE_OFFSET(addr);
4036 			addr += (offs - froffs);
4037 			addr = EHCI_PAGE(addr);
4038 			addr /= EHCI_PAGE_SIZE;
4039 
4040 			/* This gets the initial offset into the first page,
4041 			 * looks how far further along the current uframe
4042 			 * offset is. Works out how many pages that is.
4043 			 */
4044 
4045 			itd->itd.itd_ctl[j] = htole32 ( EHCI_ITD_ACTIVE |
4046 			    EHCI_ITD_SET_LEN(xfer->frlengths[trans_count]) |
4047 			    EHCI_ITD_SET_PG(addr) |
4048 			    EHCI_ITD_SET_OFFS(EHCI_PAGE_OFFSET(DMAADDR(dma_buf,offs))));
4049 
4050 			total_length += xfer->frlengths[trans_count];
4051 			offs += xfer->frlengths[trans_count];
4052 			trans_count++;
4053 
4054 			if (trans_count >= xfer->nframes) { /*Set IOC*/
4055 				itd->itd.itd_ctl[j] |= htole32(EHCI_ITD_IOC);
4056 				break;
4057 			}
4058 		}
4059 
4060 		/* Step 1.75, set buffer pointers. To simplify matters, all
4061 		 * pointers are filled out for the next 7 hardware pages in
4062 		 * the dma block, so no need to worry what pages to cover
4063 		 * and what to not.
4064 		 */
4065 
4066 		for (j = 0; j < EHCI_ITD_NBUFFERS; j++) {
4067 			/*
4068 			 * Don't try to lookup a page that's past the end
4069 			 * of buffer
4070 			 */
4071 			int page_offs = EHCI_PAGE(froffs + (EHCI_PAGE_SIZE * j));
4072 			if (page_offs >= dma_buf->block->size)
4073 				break;
4074 
4075 			unsigned long long page = DMAADDR(dma_buf, page_offs);
4076 			page = EHCI_PAGE(page);
4077 			itd->itd.itd_bufr[j] =
4078 			    htole32(EHCI_ITD_SET_BPTR(page));
4079 			itd->itd.itd_bufr_hi[j] =
4080 			    htole32(page >> 32);
4081 		}
4082 
4083 		/*
4084 		 * Other special values
4085 		 */
4086 
4087 		k = epipe->pipe.endpoint->edesc->bEndpointAddress;
4088 		itd->itd.itd_bufr[0] |= htole32(EHCI_ITD_SET_EP(UE_GET_ADDR(k)) |
4089 		    EHCI_ITD_SET_DADDR(epipe->pipe.device->address));
4090 
4091 		k = (UE_GET_DIR(epipe->pipe.endpoint->edesc->bEndpointAddress))
4092 		    ? 1 : 0;
4093 		j = UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize);
4094 		itd->itd.itd_bufr[1] |= htole32(EHCI_ITD_SET_DIR(k) |
4095 		    EHCI_ITD_SET_MAXPKT(UE_GET_SIZE(j)));
4096 
4097 		/* FIXME: handle invalid trans */
4098 		itd->itd.itd_bufr[2] |=
4099 		    htole32(EHCI_ITD_SET_MULTI(UE_GET_TRANS(j)+1));
4100 
4101 		usb_syncmem(&itd->dma,
4102 		    itd->offs + offsetof(ehci_itd_t, itd_next),
4103                     sizeof(ehci_itd_t),
4104 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4105 
4106 		prev = itd;
4107 	} /* End of frame */
4108 
4109 	stop = itd;
4110 	stop->xfer_next = NULL;
4111 	exfer->isoc_len = total_length;
4112 
4113 	usb_syncmem(&exfer->xfer.dmabuf, 0, total_length,
4114 		BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
4115 
4116 	/*
4117 	 * Part 2: Transfer descriptors have now been set up, now they must
4118 	 * be scheduled into the period frame list. Erk. Not wanting to
4119 	 * complicate matters, transfer is denied if the transfer spans
4120 	 * more than the period frame list.
4121 	 */
4122 
4123 	mutex_enter(&sc->sc_lock);
4124 
4125 	/* Start inserting frames */
4126 	if (epipe->u.isoc.cur_xfers > 0) {
4127 		frindex = epipe->u.isoc.next_frame;
4128 	} else {
4129 		frindex = EOREAD4(sc, EHCI_FRINDEX);
4130 		frindex = frindex >> 3; /* Erase microframe index */
4131 		frindex += 2;
4132 	}
4133 
4134 	if (frindex >= sc->sc_flsize)
4135 		frindex &= (sc->sc_flsize - 1);
4136 
4137 	/* What's the frame interval? */
4138 	i = (1 << (epipe->pipe.endpoint->edesc->bInterval - 1));
4139 	if (i / USB_UFRAMES_PER_FRAME == 0)
4140 		i = 1;
4141 	else
4142 		i /= USB_UFRAMES_PER_FRAME;
4143 
4144 	itd = start;
4145 	for (j = 0; j < frames; j++) {
4146 		if (itd == NULL)
4147 			panic("ehci: unexpectedly ran out of isoc itds, isoc_start\n");
4148 
4149 		itd->itd.itd_next = sc->sc_flist[frindex];
4150 		if (itd->itd.itd_next == 0)
4151 			/* FIXME: frindex table gets initialized to NULL
4152 			 * or EHCI_NULL? */
4153 			itd->itd.itd_next = EHCI_NULL;
4154 
4155 		usb_syncmem(&itd->dma,
4156 		    itd->offs + offsetof(ehci_itd_t, itd_next),
4157                     sizeof(itd->itd.itd_next),
4158 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4159 
4160 		sc->sc_flist[frindex] = htole32(EHCI_LINK_ITD | itd->physaddr);
4161 
4162 		usb_syncmem(&sc->sc_fldma,
4163 		    sizeof(ehci_link_t) * frindex,
4164                     sizeof(ehci_link_t),
4165 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4166 
4167 		itd->u.frame_list.next = sc->sc_softitds[frindex];
4168 		sc->sc_softitds[frindex] = itd;
4169 		if (itd->u.frame_list.next != NULL)
4170 			itd->u.frame_list.next->u.frame_list.prev = itd;
4171 		itd->slot = frindex;
4172 		itd->u.frame_list.prev = NULL;
4173 
4174 		frindex += i;
4175 		if (frindex >= sc->sc_flsize)
4176 			frindex -= sc->sc_flsize;
4177 
4178 		itd = itd->xfer_next;
4179 	}
4180 
4181 	epipe->u.isoc.cur_xfers++;
4182 	epipe->u.isoc.next_frame = frindex;
4183 
4184 	exfer->itdstart = start;
4185 	exfer->itdend = stop;
4186 	exfer->sqtdstart = NULL;
4187 	exfer->sqtdstart = NULL;
4188 
4189 	ehci_add_intr_list(sc, exfer);
4190 	xfer->status = USBD_IN_PROGRESS;
4191 	xfer->done = 0;
4192 	mutex_exit(&sc->sc_lock);
4193 
4194 	if (sc->sc_bus.use_polling) {
4195 		printf("Starting ehci isoc xfer with polling. Bad idea?\n");
4196 		ehci_waitintr(sc, xfer);
4197 	}
4198 
4199 	return USBD_IN_PROGRESS;
4200 }
4201 
4202 Static void
4203 ehci_device_isoc_abort(usbd_xfer_handle xfer)
4204 {
4205 	DPRINTFN(1, ("ehci_device_isoc_abort: xfer = %p\n", xfer));
4206 	ehci_abort_isoc_xfer(xfer, USBD_CANCELLED);
4207 }
4208 
4209 Static void
4210 ehci_device_isoc_close(usbd_pipe_handle pipe)
4211 {
4212 	DPRINTFN(1, ("ehci_device_isoc_close: nothing in the pipe to free?\n"));
4213 }
4214 
4215 Static void
4216 ehci_device_isoc_done(usbd_xfer_handle xfer)
4217 {
4218 	struct ehci_xfer *exfer;
4219 	ehci_softc_t *sc;
4220 	struct ehci_pipe *epipe;
4221 
4222 	exfer = EXFER(xfer);
4223 	sc = xfer->pipe->device->bus->hci_private;
4224 	epipe = (struct ehci_pipe *) xfer->pipe;
4225 
4226 	KASSERT(mutex_owned(&sc->sc_lock));
4227 
4228 	epipe->u.isoc.cur_xfers--;
4229 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(exfer)) {
4230 		ehci_del_intr_list(sc, exfer);
4231 		ehci_rem_free_itd_chain(sc, exfer);
4232 	}
4233 
4234 	usb_syncmem(&xfer->dmabuf, 0, xfer->length, BUS_DMASYNC_POSTWRITE |
4235                     BUS_DMASYNC_POSTREAD);
4236 
4237 }
4238