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