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