xref: /netbsd-src/sys/dev/usb/ehci.c (revision 6deb2c22d20de1d75d538e8a5c57b573926fd157)
1 /*	$NetBSD: ehci.c,v 1.159 2009/09/04 17:55:03 dyoung 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://developer.intel.com/technology/usb/download/ehci-r10.pdf
38  * and the USB 2.0 spec at
39  * http://www.usb.org/developers/docs/usb_20.zip
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.159 2009/09/04 17:55:03 dyoung 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 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 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 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 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 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 < 8; i++) {
815 		if (le32toh(itd->itd.itd_ctl[i]) & EHCI_ITD_ACTIVE)
816 			break;
817 	}
818 
819 	if (i == 8) {
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 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 		switch (xfer->pipe->endpoint->edesc->bInterval) {
883 		case 0:
884 			panic("ehci: isoc xfer suddenly has 0 bInterval, invalid\n");
885 		case 1: uframes = 1; break;
886 		case 2: uframes = 2; break;
887 		case 3: uframes = 4; break;
888 		default: uframes = 8; break;
889 		}
890 
891 		for (itd = ex->itdstart; itd != NULL; itd = itd->xfer_next) {
892 			usb_syncmem(&itd->dma,itd->offs + offsetof(ehci_itd_t,itd_ctl),
893 			    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_POSTWRITE |
894 			    BUS_DMASYNC_POSTREAD);
895 
896 			for (i = 0; i < 8; i += uframes) {
897 				/* XXX - driver didn't fill in the frame full
898 				 *   of uframes. This leads to scheduling
899 				 *   inefficiencies, but working around
900 				 *   this doubles complexity of tracking
901 				 *   an xfer.
902 				 */
903 				if (nframes >= xfer->nframes)
904 					break;
905 
906 				status = le32toh(itd->itd.itd_ctl[i]);
907 				len = EHCI_ITD_GET_LEN(status);
908 				if (EHCI_ITD_GET_STATUS(status) != 0)
909 					len = 0; /*No valid data on error*/
910 
911 				xfer->frlengths[nframes++] = len;
912 				actlen += len;
913 			}
914 
915 			if (nframes >= xfer->nframes)
916 				break;
917 	    	}
918 
919 		xfer->actlen = actlen;
920 		xfer->status = USBD_NORMAL_COMPLETION;
921 		goto end;
922 	}
923 
924 	/* Continue processing xfers using queue heads */
925 
926 	lsqtd = ex->sqtdend;
927 	actlen = 0;
928 	for (sqtd = ex->sqtdstart; sqtd != lsqtd->nextqtd; sqtd = sqtd->nextqtd) {
929 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
930 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
931 		nstatus = le32toh(sqtd->qtd.qtd_status);
932 		if (nstatus & EHCI_QTD_ACTIVE)
933 			break;
934 
935 		status = nstatus;
936 		if (EHCI_QTD_GET_PID(status) != EHCI_QTD_PID_SETUP)
937 			actlen += sqtd->len - EHCI_QTD_GET_BYTES(status);
938 	}
939 
940 
941 	/*
942 	 * If there are left over TDs we need to update the toggle.
943 	 * The default pipe doesn't need it since control transfers
944 	 * start the toggle at 0 every time.
945 	 * For a short transfer we need to update the toggle for the missing
946 	 * packets within the qTD.
947 	 */
948 	if ((sqtd != lsqtd->nextqtd || EHCI_QTD_GET_BYTES(status)) &&
949 	    xfer->pipe->device->default_pipe != xfer->pipe) {
950 		DPRINTFN(2, ("ehci_idone: need toggle update "
951 			     "status=%08x nstatus=%08x\n", status, nstatus));
952 #if 0
953 		ehci_dump_sqh(epipe->sqh);
954 		ehci_dump_sqtds(ex->sqtdstart);
955 #endif
956 		epipe->nexttoggle = EHCI_QTD_GET_TOGGLE(nstatus);
957 	}
958 
959 	DPRINTFN(/*10*/2, ("ehci_idone: len=%d, actlen=%d, status=0x%x\n",
960 			   xfer->length, actlen, status));
961 	xfer->actlen = actlen;
962 	if (status & EHCI_QTD_HALTED) {
963 #ifdef EHCI_DEBUG
964 		char sbuf[128];
965 
966 		snprintb(sbuf, sizeof(sbuf),
967 		    "\20\7HALTED\6BUFERR\5BABBLE\4XACTERR\3MISSED\1PINGSTATE",
968 		    (u_int32_t)status);
969 
970 		DPRINTFN(2, ("ehci_idone: error, addr=%d, endpt=0x%02x, "
971 			  "status 0x%s\n",
972 			  xfer->pipe->device->address,
973 			  xfer->pipe->endpoint->edesc->bEndpointAddress,
974 			  sbuf));
975 		if (ehcidebug > 2) {
976 			ehci_dump_sqh(epipe->sqh);
977 			ehci_dump_sqtds(ex->sqtdstart);
978 		}
979 #endif
980 		/* low&full speed has an extra error flag */
981 		if (EHCI_QH_GET_EPS(epipe->sqh->qh.qh_endp) !=
982 		    EHCI_QH_SPEED_HIGH)
983 			status &= EHCI_QTD_STATERRS | EHCI_QTD_PINGSTATE;
984 		else
985 			status &= EHCI_QTD_STATERRS;
986 		if (status == 0) /* no other errors means a stall */ {
987 			xfer->status = USBD_STALLED;
988 		} else {
989 			xfer->status = USBD_IOERROR; /* more info XXX */
990 		}
991 		/* XXX need to reset TT on missed microframe */
992 		if (status & EHCI_QTD_MISSEDMICRO) {
993 			ehci_softc_t *sc =
994 			    xfer->pipe->device->bus->hci_private;
995 
996 			printf("%s: missed microframe, TT reset not "
997 			    "implemented, hub might be inoperational\n",
998 			    device_xname(sc->sc_dev));
999 		}
1000 	} else {
1001 		xfer->status = USBD_NORMAL_COMPLETION;
1002 	}
1003 
1004     end:
1005 	/* XXX transfer_complete memcpys out transfer data (for in endpoints)
1006 	 * during this call, before methods->done is called: dma sync required
1007 	 * beforehand? */
1008 	usb_transfer_complete(xfer);
1009 	DPRINTFN(/*12*/2, ("ehci_idone: ex=%p done\n", ex));
1010 }
1011 
1012 /*
1013  * Wait here until controller claims to have an interrupt.
1014  * Then call ehci_intr and return.  Use timeout to avoid waiting
1015  * too long.
1016  */
1017 void
1018 ehci_waitintr(ehci_softc_t *sc, usbd_xfer_handle xfer)
1019 {
1020 	int timo;
1021 	u_int32_t intrs;
1022 
1023 	xfer->status = USBD_IN_PROGRESS;
1024 	for (timo = xfer->timeout; timo >= 0; timo--) {
1025 		usb_delay_ms(&sc->sc_bus, 1);
1026 		if (sc->sc_dying)
1027 			break;
1028 		intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS)) &
1029 			sc->sc_eintrs;
1030 		DPRINTFN(15,("ehci_waitintr: 0x%04x\n", intrs));
1031 #ifdef EHCI_DEBUG
1032 		if (ehcidebug > 15)
1033 			ehci_dump_regs(sc);
1034 #endif
1035 		if (intrs) {
1036 			ehci_intr1(sc);
1037 			if (xfer->status != USBD_IN_PROGRESS)
1038 				return;
1039 		}
1040 	}
1041 
1042 	/* Timeout */
1043 	DPRINTF(("ehci_waitintr: timeout\n"));
1044 	xfer->status = USBD_TIMEOUT;
1045 	usb_transfer_complete(xfer);
1046 	/* XXX should free TD */
1047 }
1048 
1049 void
1050 ehci_poll(struct usbd_bus *bus)
1051 {
1052 	ehci_softc_t *sc = bus->hci_private;
1053 #ifdef EHCI_DEBUG
1054 	static int last;
1055 	int new;
1056 	new = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
1057 	if (new != last) {
1058 		DPRINTFN(10,("ehci_poll: intrs=0x%04x\n", new));
1059 		last = new;
1060 	}
1061 #endif
1062 
1063 	if (EOREAD4(sc, EHCI_USBSTS) & sc->sc_eintrs)
1064 		ehci_intr1(sc);
1065 }
1066 
1067 void
1068 ehci_childdet(device_t self, device_t child)
1069 {
1070 	struct ehci_softc *sc = device_private(self);
1071 
1072 	KASSERT(sc->sc_child == child);
1073 	sc->sc_child = NULL;
1074 }
1075 
1076 int
1077 ehci_detach(struct ehci_softc *sc, int flags)
1078 {
1079 	int rv = 0;
1080 
1081 	if (sc->sc_child != NULL)
1082 		rv = config_detach(sc->sc_child, flags);
1083 
1084 	if (rv != 0)
1085 		return (rv);
1086 
1087         callout_stop(&(sc->sc_tmo_intrlist));
1088 
1089 	usb_delay_ms(&sc->sc_bus, 300); /* XXX let stray task complete */
1090 
1091 	/* XXX free other data structures XXX */
1092 	mutex_destroy(&sc->sc_doorbell_lock);
1093 	mutex_destroy(&sc->sc_intrhead_lock);
1094 
1095 	EOWRITE4(sc, EHCI_CONFIGFLAG, 0);
1096 
1097 	return (rv);
1098 }
1099 
1100 
1101 int
1102 ehci_activate(device_t self, enum devact act)
1103 {
1104 	struct ehci_softc *sc = device_private(self);
1105 	int rv = 0;
1106 
1107 	switch (act) {
1108 	case DVACT_ACTIVATE:
1109 		return (EOPNOTSUPP);
1110 
1111 	case DVACT_DEACTIVATE:
1112 		sc->sc_dying = 1;
1113 		if (sc->sc_child != NULL)
1114 			rv = config_deactivate(sc->sc_child);
1115 		break;
1116 	}
1117 	return (rv);
1118 }
1119 
1120 /*
1121  * Handle suspend/resume.
1122  *
1123  * We need to switch to polling mode here, because this routine is
1124  * called from an interrupt context.  This is all right since we
1125  * are almost suspended anyway.
1126  *
1127  * Note that this power handler isn't to be registered directly; the
1128  * bus glue needs to call out to it.
1129  */
1130 bool
1131 ehci_suspend(device_t dv PMF_FN_ARGS)
1132 {
1133 	ehci_softc_t *sc = device_private(dv);
1134 	int i, s;
1135 	uint32_t cmd, hcr;
1136 
1137 	s = splhardusb();
1138 
1139 	sc->sc_bus.use_polling++;
1140 
1141 	for (i = 1; i <= sc->sc_noport; i++) {
1142 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1143 		if ((cmd & EHCI_PS_PO) == 0 && (cmd & EHCI_PS_PE) == EHCI_PS_PE)
1144 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_SUSP);
1145 	}
1146 
1147 	sc->sc_cmd = EOREAD4(sc, EHCI_USBCMD);
1148 
1149 	cmd = sc->sc_cmd & ~(EHCI_CMD_ASE | EHCI_CMD_PSE);
1150 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1151 
1152 	for (i = 0; i < 100; i++) {
1153 		hcr = EOREAD4(sc, EHCI_USBSTS) & (EHCI_STS_ASS | EHCI_STS_PSS);
1154 		if (hcr == 0)
1155 			break;
1156 
1157 		usb_delay_ms(&sc->sc_bus, 1);
1158 	}
1159 	if (hcr != 0)
1160 		printf("%s: reset timeout\n", device_xname(dv));
1161 
1162 	cmd &= ~EHCI_CMD_RS;
1163 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1164 
1165 	for (i = 0; i < 100; i++) {
1166 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1167 		if (hcr == EHCI_STS_HCH)
1168 			break;
1169 
1170 		usb_delay_ms(&sc->sc_bus, 1);
1171 	}
1172 	if (hcr != EHCI_STS_HCH)
1173 		printf("%s: config timeout\n", device_xname(dv));
1174 
1175 	sc->sc_bus.use_polling--;
1176 	splx(s);
1177 
1178 	return true;
1179 }
1180 
1181 bool
1182 ehci_resume(device_t dv PMF_FN_ARGS)
1183 {
1184 	ehci_softc_t *sc = device_private(dv);
1185 	int i;
1186 	uint32_t cmd, hcr;
1187 
1188 	/* restore things in case the bios sucks */
1189 	EOWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);
1190 	EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));
1191 	EOWRITE4(sc, EHCI_ASYNCLISTADDR,
1192 	    sc->sc_async_head->physaddr | EHCI_LINK_QH);
1193 
1194 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs & ~EHCI_INTR_PCIE);
1195 
1196 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1197 
1198 	hcr = 0;
1199 	for (i = 1; i <= sc->sc_noport; i++) {
1200 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1201 		if ((cmd & EHCI_PS_PO) == 0 &&
1202 		    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP) {
1203 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_FPR);
1204 			hcr = 1;
1205 		}
1206 	}
1207 
1208 	if (hcr) {
1209 		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
1210 
1211 		for (i = 1; i <= sc->sc_noport; i++) {
1212 			cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1213 			if ((cmd & EHCI_PS_PO) == 0 &&
1214 			    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP)
1215 				EOWRITE4(sc, EHCI_PORTSC(i),
1216 				    cmd & ~EHCI_PS_FPR);
1217 		}
1218 	}
1219 
1220 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1221 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
1222 
1223 	for (i = 0; i < 100; i++) {
1224 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1225 		if (hcr != EHCI_STS_HCH)
1226 			break;
1227 
1228 		usb_delay_ms(&sc->sc_bus, 1);
1229 	}
1230 	if (hcr == EHCI_STS_HCH)
1231 		printf("%s: config timeout\n", device_xname(dv));
1232 
1233 	return true;
1234 }
1235 
1236 /*
1237  * Shut down the controller when the system is going down.
1238  */
1239 bool
1240 ehci_shutdown(device_t self, int flags)
1241 {
1242 	ehci_softc_t *sc = device_private(self);
1243 
1244 	DPRINTF(("ehci_shutdown: stopping the HC\n"));
1245 	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
1246 	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
1247 	return true;
1248 }
1249 
1250 usbd_status
1251 ehci_allocm(struct usbd_bus *bus, usb_dma_t *dma, u_int32_t size)
1252 {
1253 	struct ehci_softc *sc = bus->hci_private;
1254 	usbd_status err;
1255 
1256 	err = usb_allocmem(&sc->sc_bus, size, 0, dma);
1257 	if (err == USBD_NOMEM)
1258 		err = usb_reserve_allocm(&sc->sc_dma_reserve, dma, size);
1259 #ifdef EHCI_DEBUG
1260 	if (err)
1261 		printf("ehci_allocm: usb_allocmem()=%d\n", err);
1262 #endif
1263 	return (err);
1264 }
1265 
1266 void
1267 ehci_freem(struct usbd_bus *bus, usb_dma_t *dma)
1268 {
1269 	struct ehci_softc *sc = bus->hci_private;
1270 
1271 	if (dma->block->flags & USB_DMA_RESERVE) {
1272 		usb_reserve_freem(&sc->sc_dma_reserve,
1273 		    dma);
1274 		return;
1275 	}
1276 	usb_freemem(&sc->sc_bus, dma);
1277 }
1278 
1279 usbd_xfer_handle
1280 ehci_allocx(struct usbd_bus *bus)
1281 {
1282 	struct ehci_softc *sc = bus->hci_private;
1283 	usbd_xfer_handle xfer;
1284 
1285 	xfer = SIMPLEQ_FIRST(&sc->sc_free_xfers);
1286 	if (xfer != NULL) {
1287 		SIMPLEQ_REMOVE_HEAD(&sc->sc_free_xfers, next);
1288 #ifdef DIAGNOSTIC
1289 		if (xfer->busy_free != XFER_FREE) {
1290 			printf("ehci_allocx: xfer=%p not free, 0x%08x\n", xfer,
1291 			       xfer->busy_free);
1292 		}
1293 #endif
1294 	} else {
1295 		xfer = malloc(sizeof(struct ehci_xfer), M_USB, M_NOWAIT);
1296 	}
1297 	if (xfer != NULL) {
1298 		memset(xfer, 0, sizeof(struct ehci_xfer));
1299 #ifdef DIAGNOSTIC
1300 		EXFER(xfer)->isdone = 1;
1301 		xfer->busy_free = XFER_BUSY;
1302 #endif
1303 	}
1304 	return (xfer);
1305 }
1306 
1307 void
1308 ehci_freex(struct usbd_bus *bus, usbd_xfer_handle xfer)
1309 {
1310 	struct ehci_softc *sc = bus->hci_private;
1311 
1312 #ifdef DIAGNOSTIC
1313 	if (xfer->busy_free != XFER_BUSY) {
1314 		printf("ehci_freex: xfer=%p not busy, 0x%08x\n", xfer,
1315 		       xfer->busy_free);
1316 	}
1317 	xfer->busy_free = XFER_FREE;
1318 	if (!EXFER(xfer)->isdone) {
1319 		printf("ehci_freex: !isdone\n");
1320 	}
1321 #endif
1322 	SIMPLEQ_INSERT_HEAD(&sc->sc_free_xfers, xfer, next);
1323 }
1324 
1325 Static void
1326 ehci_device_clear_toggle(usbd_pipe_handle pipe)
1327 {
1328 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
1329 
1330 	DPRINTF(("ehci_device_clear_toggle: epipe=%p status=0x%x\n",
1331 		 epipe, epipe->sqh->qh.qh_qtd.qtd_status));
1332 #ifdef EHCI_DEBUG
1333 	if (ehcidebug)
1334 		usbd_dump_pipe(pipe);
1335 #endif
1336 	epipe->nexttoggle = 0;
1337 }
1338 
1339 Static void
1340 ehci_noop(usbd_pipe_handle pipe)
1341 {
1342 }
1343 
1344 #ifdef EHCI_DEBUG
1345 void
1346 ehci_dump_regs(ehci_softc_t *sc)
1347 {
1348 	int i;
1349 	printf("cmd=0x%08x, sts=0x%08x, ien=0x%08x\n",
1350 	       EOREAD4(sc, EHCI_USBCMD),
1351 	       EOREAD4(sc, EHCI_USBSTS),
1352 	       EOREAD4(sc, EHCI_USBINTR));
1353 	printf("frindex=0x%08x ctrdsegm=0x%08x periodic=0x%08x async=0x%08x\n",
1354 	       EOREAD4(sc, EHCI_FRINDEX),
1355 	       EOREAD4(sc, EHCI_CTRLDSSEGMENT),
1356 	       EOREAD4(sc, EHCI_PERIODICLISTBASE),
1357 	       EOREAD4(sc, EHCI_ASYNCLISTADDR));
1358 	for (i = 1; i <= sc->sc_noport; i++)
1359 		printf("port %d status=0x%08x\n", i,
1360 		       EOREAD4(sc, EHCI_PORTSC(i)));
1361 }
1362 
1363 /*
1364  * Unused function - this is meant to be called from a kernel
1365  * debugger.
1366  */
1367 void
1368 ehci_dump(void)
1369 {
1370 	ehci_dump_regs(theehci);
1371 }
1372 
1373 void
1374 ehci_dump_link(ehci_link_t link, int type)
1375 {
1376 	link = le32toh(link);
1377 	printf("0x%08x", link);
1378 	if (link & EHCI_LINK_TERMINATE)
1379 		printf("<T>");
1380 	else {
1381 		printf("<");
1382 		if (type) {
1383 			switch (EHCI_LINK_TYPE(link)) {
1384 			case EHCI_LINK_ITD: printf("ITD"); break;
1385 			case EHCI_LINK_QH: printf("QH"); break;
1386 			case EHCI_LINK_SITD: printf("SITD"); break;
1387 			case EHCI_LINK_FSTN: printf("FSTN"); break;
1388 			}
1389 		}
1390 		printf(">");
1391 	}
1392 }
1393 
1394 void
1395 ehci_dump_sqtds(ehci_soft_qtd_t *sqtd)
1396 {
1397 	int i;
1398 	u_int32_t stop;
1399 
1400 	stop = 0;
1401 	for (i = 0; sqtd && i < 20 && !stop; sqtd = sqtd->nextqtd, i++) {
1402 		ehci_dump_sqtd(sqtd);
1403 		usb_syncmem(&sqtd->dma,
1404 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1405 		    sizeof(sqtd->qtd),
1406 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1407 		stop = sqtd->qtd.qtd_next & htole32(EHCI_LINK_TERMINATE);
1408 		usb_syncmem(&sqtd->dma,
1409 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1410 		    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1411 	}
1412 	if (sqtd)
1413 		printf("dump aborted, too many TDs\n");
1414 }
1415 
1416 void
1417 ehci_dump_sqtd(ehci_soft_qtd_t *sqtd)
1418 {
1419 	usb_syncmem(&sqtd->dma, sqtd->offs,
1420 	    sizeof(sqtd->qtd), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1421 	printf("QTD(%p) at 0x%08x:\n", sqtd, sqtd->physaddr);
1422 	ehci_dump_qtd(&sqtd->qtd);
1423 	usb_syncmem(&sqtd->dma, sqtd->offs,
1424 	    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1425 }
1426 
1427 void
1428 ehci_dump_qtd(ehci_qtd_t *qtd)
1429 {
1430 	u_int32_t s;
1431 	char sbuf[128];
1432 
1433 	printf("  next="); ehci_dump_link(qtd->qtd_next, 0);
1434 	printf(" altnext="); ehci_dump_link(qtd->qtd_altnext, 0);
1435 	printf("\n");
1436 	s = le32toh(qtd->qtd_status);
1437 	snprintb(sbuf, sizeof(sbuf),
1438 	    "\20\10ACTIVE\7HALTED\6BUFERR\5BABBLE\4XACTERR"
1439 	    "\3MISSED\2SPLIT\1PING", EHCI_QTD_GET_STATUS(s));
1440 	printf("  status=0x%08x: toggle=%d bytes=0x%x ioc=%d c_page=0x%x\n",
1441 	       s, EHCI_QTD_GET_TOGGLE(s), EHCI_QTD_GET_BYTES(s),
1442 	       EHCI_QTD_GET_IOC(s), EHCI_QTD_GET_C_PAGE(s));
1443 	printf("    cerr=%d pid=%d stat=0x%s\n", EHCI_QTD_GET_CERR(s),
1444 	       EHCI_QTD_GET_PID(s), sbuf);
1445 	for (s = 0; s < 5; s++)
1446 		printf("  buffer[%d]=0x%08x\n", s, le32toh(qtd->qtd_buffer[s]));
1447 }
1448 
1449 void
1450 ehci_dump_sqh(ehci_soft_qh_t *sqh)
1451 {
1452 	ehci_qh_t *qh = &sqh->qh;
1453 	u_int32_t endp, endphub;
1454 
1455 	usb_syncmem(&sqh->dma, sqh->offs,
1456 	    sizeof(sqh->qh), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1457 	printf("QH(%p) at 0x%08x:\n", sqh, sqh->physaddr);
1458 	printf("  link="); ehci_dump_link(qh->qh_link, 1); printf("\n");
1459 	endp = le32toh(qh->qh_endp);
1460 	printf("  endp=0x%08x\n", endp);
1461 	printf("    addr=0x%02x inact=%d endpt=%d eps=%d dtc=%d hrecl=%d\n",
1462 	       EHCI_QH_GET_ADDR(endp), EHCI_QH_GET_INACT(endp),
1463 	       EHCI_QH_GET_ENDPT(endp),  EHCI_QH_GET_EPS(endp),
1464 	       EHCI_QH_GET_DTC(endp), EHCI_QH_GET_HRECL(endp));
1465 	printf("    mpl=0x%x ctl=%d nrl=%d\n",
1466 	       EHCI_QH_GET_MPL(endp), EHCI_QH_GET_CTL(endp),
1467 	       EHCI_QH_GET_NRL(endp));
1468 	endphub = le32toh(qh->qh_endphub);
1469 	printf("  endphub=0x%08x\n", endphub);
1470 	printf("    smask=0x%02x cmask=0x%02x huba=0x%02x port=%d mult=%d\n",
1471 	       EHCI_QH_GET_SMASK(endphub), EHCI_QH_GET_CMASK(endphub),
1472 	       EHCI_QH_GET_HUBA(endphub), EHCI_QH_GET_PORT(endphub),
1473 	       EHCI_QH_GET_MULT(endphub));
1474 	printf("  curqtd="); ehci_dump_link(qh->qh_curqtd, 0); printf("\n");
1475 	printf("Overlay qTD:\n");
1476 	ehci_dump_qtd(&qh->qh_qtd);
1477 	usb_syncmem(&sqh->dma, sqh->offs,
1478 	    sizeof(sqh->qh), BUS_DMASYNC_PREREAD);
1479 }
1480 
1481 #if notyet
1482 void
1483 ehci_dump_itd(struct ehci_soft_itd *itd)
1484 {
1485 	ehci_isoc_trans_t t;
1486 	ehci_isoc_bufr_ptr_t b, b2, b3;
1487 	int i;
1488 
1489 	printf("ITD: next phys=%X\n", itd->itd.itd_next);
1490 
1491 	for (i = 0; i < 8;i++) {
1492 		t = le32toh(itd->itd.itd_ctl[i]);
1493 		printf("ITDctl %d: stat=%X len=%X ioc=%X pg=%X offs=%X\n", i,
1494 		    EHCI_ITD_GET_STATUS(t), EHCI_ITD_GET_LEN(t),
1495 		    EHCI_ITD_GET_IOC(t), EHCI_ITD_GET_PG(t),
1496 		    EHCI_ITD_GET_OFFS(t));
1497 	}
1498 	printf("ITDbufr: ");
1499 	for (i = 0; i < 7; i++)
1500 		printf("%X,", EHCI_ITD_GET_BPTR(le32toh(itd->itd.itd_bufr[i])));
1501 
1502 	b = le32toh(itd->itd.itd_bufr[0]);
1503 	b2 = le32toh(itd->itd.itd_bufr[1]);
1504 	b3 = le32toh(itd->itd.itd_bufr[2]);
1505 	printf("\nep=%X daddr=%X dir=%d maxpkt=%X multi=%X\n",
1506 	    EHCI_ITD_GET_EP(b), EHCI_ITD_GET_DADDR(b), EHCI_ITD_GET_DIR(b2),
1507 	    EHCI_ITD_GET_MAXPKT(b2), EHCI_ITD_GET_MULTI(b3));
1508 }
1509 
1510 void
1511 ehci_dump_sitd(struct ehci_soft_itd *itd)
1512 {
1513 	printf("SITD %p next=%p prev=%p xfernext=%p physaddr=%X slot=%d\n",
1514 			itd, itd->u.frame_list.next, itd->u.frame_list.prev,
1515 			itd->xfer_next, itd->physaddr, itd->slot);
1516 }
1517 #endif
1518 
1519 #ifdef DIAGNOSTIC
1520 void
1521 ehci_dump_exfer(struct ehci_xfer *ex)
1522 {
1523 	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);
1524 }
1525 #endif
1526 #endif
1527 
1528 usbd_status
1529 ehci_open(usbd_pipe_handle pipe)
1530 {
1531 	usbd_device_handle dev = pipe->device;
1532 	ehci_softc_t *sc = dev->bus->hci_private;
1533 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1534 	u_int8_t addr = dev->address;
1535 	u_int8_t xfertype = ed->bmAttributes & UE_XFERTYPE;
1536 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
1537 	ehci_soft_qh_t *sqh;
1538 	usbd_status err;
1539 	int s;
1540 	int ival, speed, naks;
1541 	int hshubaddr, hshubport;
1542 
1543 	DPRINTFN(1, ("ehci_open: pipe=%p, addr=%d, endpt=%d (%d)\n",
1544 		     pipe, addr, ed->bEndpointAddress, sc->sc_addr));
1545 
1546 	if (dev->myhsport) {
1547 		hshubaddr = dev->myhsport->parent->address;
1548 		hshubport = dev->myhsport->portno;
1549 	} else {
1550 		hshubaddr = 0;
1551 		hshubport = 0;
1552 	}
1553 
1554 	if (sc->sc_dying)
1555 		return (USBD_IOERROR);
1556 
1557 	epipe->nexttoggle = 0;
1558 
1559 	if (addr == sc->sc_addr) {
1560 		switch (ed->bEndpointAddress) {
1561 		case USB_CONTROL_ENDPOINT:
1562 			pipe->methods = &ehci_root_ctrl_methods;
1563 			break;
1564 		case UE_DIR_IN | EHCI_INTR_ENDPT:
1565 			pipe->methods = &ehci_root_intr_methods;
1566 			break;
1567 		default:
1568 			DPRINTF(("ehci_open: bad bEndpointAddress 0x%02x\n",
1569 			    ed->bEndpointAddress));
1570 			return (USBD_INVAL);
1571 		}
1572 		return (USBD_NORMAL_COMPLETION);
1573 	}
1574 
1575 	/* XXX All this stuff is only valid for async. */
1576 	switch (dev->speed) {
1577 	case USB_SPEED_LOW:  speed = EHCI_QH_SPEED_LOW;  break;
1578 	case USB_SPEED_FULL: speed = EHCI_QH_SPEED_FULL; break;
1579 	case USB_SPEED_HIGH: speed = EHCI_QH_SPEED_HIGH; break;
1580 	default: panic("ehci_open: bad device speed %d", dev->speed);
1581 	}
1582 	if (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_ISOCHRONOUS) {
1583 		aprint_error_dev(sc->sc_dev, "error opening low/full speed "
1584 		    "isoc endpoint.\n");
1585 		aprint_normal_dev(sc->sc_dev, "a low/full speed device is "
1586 		    "attached to a USB2 hub, and transaction translations are "
1587 		    "not yet supported.\n");
1588 		aprint_normal_dev(sc->sc_dev, "reattach the device to the "
1589 		    "root hub instead.\n");
1590 		DPRINTFN(1,("ehci_open: hshubaddr=%d hshubport=%d\n",
1591 			    hshubaddr, hshubport));
1592 		return USBD_INVAL;
1593 	}
1594 
1595 	naks = 8;		/* XXX */
1596 
1597 	/* Allocate sqh for everything, save isoc xfers */
1598 	if (xfertype != UE_ISOCHRONOUS) {
1599 		sqh = ehci_alloc_sqh(sc);
1600 		if (sqh == NULL)
1601 			return (USBD_NOMEM);
1602 		/* qh_link filled when the QH is added */
1603 		sqh->qh.qh_endp = htole32(
1604 		    EHCI_QH_SET_ADDR(addr) |
1605 		    EHCI_QH_SET_ENDPT(UE_GET_ADDR(ed->bEndpointAddress)) |
1606 		    EHCI_QH_SET_EPS(speed) |
1607 		    EHCI_QH_DTC |
1608 		    EHCI_QH_SET_MPL(UGETW(ed->wMaxPacketSize)) |
1609 		    (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_CONTROL ?
1610 		     EHCI_QH_CTL : 0) |
1611 		    EHCI_QH_SET_NRL(naks)
1612 		    );
1613 		sqh->qh.qh_endphub = htole32(
1614 		    EHCI_QH_SET_MULT(1) |
1615 		    EHCI_QH_SET_HUBA(hshubaddr) |
1616 		    EHCI_QH_SET_PORT(hshubport) |
1617 		    EHCI_QH_SET_CMASK(0x08) | /* XXX */
1618 		    EHCI_QH_SET_SMASK(xfertype == UE_INTERRUPT ? 0x02 : 0)
1619 		    );
1620 		sqh->qh.qh_curqtd = EHCI_NULL;
1621 		/* Fill the overlay qTD */
1622 		sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
1623 		sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
1624 		sqh->qh.qh_qtd.qtd_status = htole32(0);
1625 
1626 		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1627 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1628 		epipe->sqh = sqh;
1629 	} else {
1630 		sqh = NULL;
1631 	} /*xfertype == UE_ISOC*/
1632 
1633 	switch (xfertype) {
1634 	case UE_CONTROL:
1635 		err = usb_allocmem(&sc->sc_bus, sizeof(usb_device_request_t),
1636 				   0, &epipe->u.ctl.reqdma);
1637 #ifdef EHCI_DEBUG
1638 		if (err)
1639 			printf("ehci_open: usb_allocmem()=%d\n", err);
1640 #endif
1641 		if (err)
1642 			goto bad;
1643 		pipe->methods = &ehci_device_ctrl_methods;
1644 		s = splusb();
1645 		ehci_add_qh(sqh, sc->sc_async_head);
1646 		splx(s);
1647 		break;
1648 	case UE_BULK:
1649 		pipe->methods = &ehci_device_bulk_methods;
1650 		s = splusb();
1651 		ehci_add_qh(sqh, sc->sc_async_head);
1652 		splx(s);
1653 		break;
1654 	case UE_INTERRUPT:
1655 		pipe->methods = &ehci_device_intr_methods;
1656 		ival = pipe->interval;
1657 		if (ival == USBD_DEFAULT_INTERVAL) {
1658 			if (speed == EHCI_QH_SPEED_HIGH) {
1659 				if (ed->bInterval > 16) {
1660 					/*
1661 					 * illegal with high-speed, but there
1662 					 * were documentation bugs in the spec,
1663 					 * so be generous
1664 					 */
1665 					ival = 256;
1666 				} else
1667 					ival = (1 << (ed->bInterval - 1)) / 8;
1668 			} else
1669 				ival = ed->bInterval;
1670 		}
1671 		err = ehci_device_setintr(sc, sqh, ival);
1672 		if (err)
1673 			goto bad;
1674 		break;
1675 	case UE_ISOCHRONOUS:
1676 		pipe->methods = &ehci_device_isoc_methods;
1677 		if (ed->bInterval == 0 || ed->bInterval > 16) {
1678 			printf("ehci: opening pipe with invalid bInterval\n");
1679 			err = USBD_INVAL;
1680 			goto bad;
1681 		}
1682 		if (UGETW(ed->wMaxPacketSize) == 0) {
1683 			printf("ehci: zero length endpoint open request\n");
1684 			err = USBD_INVAL;
1685 			goto bad;
1686 		}
1687 		epipe->u.isoc.next_frame = 0;
1688 		epipe->u.isoc.cur_xfers = 0;
1689 		break;
1690 	default:
1691 		DPRINTF(("ehci: bad xfer type %d\n", xfertype));
1692 		err = USBD_INVAL;
1693 		goto bad;
1694 	}
1695 	return (USBD_NORMAL_COMPLETION);
1696 
1697  bad:
1698 	if (sqh != NULL)
1699 		ehci_free_sqh(sc, sqh);
1700 	return (err);
1701 }
1702 
1703 /*
1704  * Add an ED to the schedule.  Called at splusb().
1705  */
1706 void
1707 ehci_add_qh(ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
1708 {
1709 	SPLUSBCHECK;
1710 
1711 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
1712 	    sizeof(head->qh.qh_link), BUS_DMASYNC_POSTWRITE);
1713 	sqh->next = head->next;
1714 	sqh->qh.qh_link = head->qh.qh_link;
1715 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
1716 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_PREWRITE);
1717 	head->next = sqh;
1718 	head->qh.qh_link = htole32(sqh->physaddr | EHCI_LINK_QH);
1719 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
1720 	    sizeof(head->qh.qh_link), BUS_DMASYNC_PREWRITE);
1721 
1722 #ifdef EHCI_DEBUG
1723 	if (ehcidebug > 5) {
1724 		printf("ehci_add_qh:\n");
1725 		ehci_dump_sqh(sqh);
1726 	}
1727 #endif
1728 }
1729 
1730 /*
1731  * Remove an ED from the schedule.  Called at splusb().
1732  */
1733 void
1734 ehci_rem_qh(ehci_softc_t *sc, ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
1735 {
1736 	ehci_soft_qh_t *p;
1737 
1738 	SPLUSBCHECK;
1739 	/* XXX */
1740 	for (p = head; p != NULL && p->next != sqh; p = p->next)
1741 		;
1742 	if (p == NULL)
1743 		panic("ehci_rem_qh: ED not found");
1744 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
1745 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_POSTWRITE);
1746 	p->next = sqh->next;
1747 	p->qh.qh_link = sqh->qh.qh_link;
1748 	usb_syncmem(&p->dma, p->offs + offsetof(ehci_qh_t, qh_link),
1749 	    sizeof(p->qh.qh_link), BUS_DMASYNC_PREWRITE);
1750 
1751 	ehci_sync_hc(sc);
1752 }
1753 
1754 void
1755 ehci_set_qh_qtd(ehci_soft_qh_t *sqh, ehci_soft_qtd_t *sqtd)
1756 {
1757 	int i;
1758 	u_int32_t status;
1759 
1760 	/* Save toggle bit and ping status. */
1761 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1762 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1763 	status = sqh->qh.qh_qtd.qtd_status &
1764 	    htole32(EHCI_QTD_TOGGLE_MASK |
1765 		    EHCI_QTD_SET_STATUS(EHCI_QTD_PINGSTATE));
1766 	/* Set HALTED to make hw leave it alone. */
1767 	sqh->qh.qh_qtd.qtd_status =
1768 	    htole32(EHCI_QTD_SET_STATUS(EHCI_QTD_HALTED));
1769 	usb_syncmem(&sqh->dma,
1770 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
1771 	    sizeof(sqh->qh.qh_qtd.qtd_status),
1772 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1773 	sqh->qh.qh_curqtd = 0;
1774 	sqh->qh.qh_qtd.qtd_next = htole32(sqtd->physaddr);
1775 	sqh->qh.qh_qtd.qtd_altnext = 0;
1776 	for (i = 0; i < EHCI_QTD_NBUFFERS; i++)
1777 		sqh->qh.qh_qtd.qtd_buffer[i] = 0;
1778 	sqh->sqtd = sqtd;
1779 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1780 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1781 	/* Set !HALTED && !ACTIVE to start execution, preserve some fields */
1782 	sqh->qh.qh_qtd.qtd_status = status;
1783 	usb_syncmem(&sqh->dma,
1784 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
1785 	    sizeof(sqh->qh.qh_qtd.qtd_status),
1786 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1787 }
1788 
1789 /*
1790  * Ensure that the HC has released all references to the QH.  We do this
1791  * by asking for a Async Advance Doorbell interrupt and then we wait for
1792  * the interrupt.
1793  * To make this easier we first obtain exclusive use of the doorbell.
1794  */
1795 void
1796 ehci_sync_hc(ehci_softc_t *sc)
1797 {
1798 	int s, error;
1799 
1800 	if (sc->sc_dying) {
1801 		DPRINTFN(2,("ehci_sync_hc: dying\n"));
1802 		return;
1803 	}
1804 	DPRINTFN(2,("ehci_sync_hc: enter\n"));
1805 	mutex_enter(&sc->sc_doorbell_lock);	/* get doorbell */
1806 	s = splhardusb();
1807 	/* ask for doorbell */
1808 	EOWRITE4(sc, EHCI_USBCMD, EOREAD4(sc, EHCI_USBCMD) | EHCI_CMD_IAAD);
1809 	DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
1810 		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
1811 	error = tsleep(&sc->sc_async_head, PZERO, "ehcidi", hz); /* bell wait */
1812 	DPRINTFN(1,("ehci_sync_hc: cmd=0x%08x sts=0x%08x\n",
1813 		    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS)));
1814 	splx(s);
1815 	mutex_exit(&sc->sc_doorbell_lock);	/* release doorbell */
1816 #ifdef DIAGNOSTIC
1817 	if (error)
1818 		printf("ehci_sync_hc: tsleep() = %d\n", error);
1819 #endif
1820 	DPRINTFN(2,("ehci_sync_hc: exit\n"));
1821 }
1822 
1823 /*Call at splusb*/
1824 void
1825 ehci_rem_free_itd_chain(ehci_softc_t *sc, struct ehci_xfer *exfer)
1826 {
1827 	struct ehci_soft_itd *itd, *prev;
1828 
1829 	prev = NULL;
1830 
1831 	if (exfer->itdstart == NULL || exfer->itdend == NULL)
1832 		panic("ehci isoc xfer being freed, but with no itd chain\n");
1833 
1834 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
1835 		prev = itd->u.frame_list.prev;
1836 		/* Unlink itd from hardware chain, or frame array */
1837 		if (prev == NULL) { /* We're at the table head */
1838 			sc->sc_softitds[itd->slot] = itd->u.frame_list.next;
1839 			sc->sc_flist[itd->slot] = itd->itd.itd_next;
1840 			usb_syncmem(&sc->sc_fldma,
1841 			    sizeof(ehci_link_t) * itd->slot,
1842                 	    sizeof(ehci_link_t),
1843 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1844 
1845 			if (itd->u.frame_list.next != NULL)
1846 				itd->u.frame_list.next->u.frame_list.prev = NULL;
1847 		} else {
1848 			/* XXX this part is untested... */
1849 			prev->itd.itd_next = itd->itd.itd_next;
1850 			usb_syncmem(&itd->dma,
1851 			    itd->offs + offsetof(ehci_itd_t, itd_next),
1852                 	    sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE);
1853 
1854 			prev->u.frame_list.next = itd->u.frame_list.next;
1855 			if (itd->u.frame_list.next != NULL)
1856 				itd->u.frame_list.next->u.frame_list.prev = prev;
1857 		}
1858 	}
1859 
1860 	prev = NULL;
1861 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
1862 		if (prev != NULL)
1863 			ehci_free_itd(sc, prev);
1864 		prev = itd;
1865 	}
1866 	if (prev)
1867 		ehci_free_itd(sc, prev);
1868 	exfer->itdstart = NULL;
1869 	exfer->itdend = NULL;
1870 }
1871 
1872 /***********/
1873 
1874 /*
1875  * Data structures and routines to emulate the root hub.
1876  */
1877 Static usb_device_descriptor_t ehci_devd = {
1878 	USB_DEVICE_DESCRIPTOR_SIZE,
1879 	UDESC_DEVICE,		/* type */
1880 	{0x00, 0x02},		/* USB version */
1881 	UDCLASS_HUB,		/* class */
1882 	UDSUBCLASS_HUB,		/* subclass */
1883 	UDPROTO_HSHUBSTT,	/* protocol */
1884 	64,			/* max packet */
1885 	{0},{0},{0x00,0x01},	/* device id */
1886 	1,2,0,			/* string indicies */
1887 	1			/* # of configurations */
1888 };
1889 
1890 Static const usb_device_qualifier_t ehci_odevd = {
1891 	USB_DEVICE_DESCRIPTOR_SIZE,
1892 	UDESC_DEVICE_QUALIFIER,	/* type */
1893 	{0x00, 0x02},		/* USB version */
1894 	UDCLASS_HUB,		/* class */
1895 	UDSUBCLASS_HUB,		/* subclass */
1896 	UDPROTO_FSHUB,		/* protocol */
1897 	64,			/* max packet */
1898 	1,			/* # of configurations */
1899 	0
1900 };
1901 
1902 Static const usb_config_descriptor_t ehci_confd = {
1903 	USB_CONFIG_DESCRIPTOR_SIZE,
1904 	UDESC_CONFIG,
1905 	{USB_CONFIG_DESCRIPTOR_SIZE +
1906 	 USB_INTERFACE_DESCRIPTOR_SIZE +
1907 	 USB_ENDPOINT_DESCRIPTOR_SIZE},
1908 	1,
1909 	1,
1910 	0,
1911 	UC_ATTR_MBO | UC_SELF_POWERED,
1912 	0			/* max power */
1913 };
1914 
1915 Static const usb_interface_descriptor_t ehci_ifcd = {
1916 	USB_INTERFACE_DESCRIPTOR_SIZE,
1917 	UDESC_INTERFACE,
1918 	0,
1919 	0,
1920 	1,
1921 	UICLASS_HUB,
1922 	UISUBCLASS_HUB,
1923 	UIPROTO_HSHUBSTT,
1924 	0
1925 };
1926 
1927 Static const usb_endpoint_descriptor_t ehci_endpd = {
1928 	USB_ENDPOINT_DESCRIPTOR_SIZE,
1929 	UDESC_ENDPOINT,
1930 	UE_DIR_IN | EHCI_INTR_ENDPT,
1931 	UE_INTERRUPT,
1932 	{8, 0},			/* max packet */
1933 	12
1934 };
1935 
1936 Static const usb_hub_descriptor_t ehci_hubd = {
1937 	USB_HUB_DESCRIPTOR_SIZE,
1938 	UDESC_HUB,
1939 	0,
1940 	{0,0},
1941 	0,
1942 	0,
1943 	{""},
1944 	{""},
1945 };
1946 
1947 /*
1948  * Simulate a hardware hub by handling all the necessary requests.
1949  */
1950 Static usbd_status
1951 ehci_root_ctrl_transfer(usbd_xfer_handle xfer)
1952 {
1953 	usbd_status err;
1954 
1955 	/* Insert last in queue. */
1956 	err = usb_insert_transfer(xfer);
1957 	if (err)
1958 		return (err);
1959 
1960 	/* Pipe isn't running, start first */
1961 	return (ehci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
1962 }
1963 
1964 Static usbd_status
1965 ehci_root_ctrl_start(usbd_xfer_handle xfer)
1966 {
1967 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
1968 	usb_device_request_t *req;
1969 	void *buf = NULL;
1970 	int port, i;
1971 	int s, len, value, index, l, totlen = 0;
1972 	usb_port_status_t ps;
1973 	usb_hub_descriptor_t hubd;
1974 	usbd_status err;
1975 	u_int32_t v;
1976 
1977 	if (sc->sc_dying)
1978 		return (USBD_IOERROR);
1979 
1980 #ifdef DIAGNOSTIC
1981 	if (!(xfer->rqflags & URQ_REQUEST))
1982 		/* XXX panic */
1983 		return (USBD_INVAL);
1984 #endif
1985 	req = &xfer->request;
1986 
1987 	DPRINTFN(4,("ehci_root_ctrl_start: type=0x%02x request=%02x\n",
1988 		    req->bmRequestType, req->bRequest));
1989 
1990 	len = UGETW(req->wLength);
1991 	value = UGETW(req->wValue);
1992 	index = UGETW(req->wIndex);
1993 
1994 	if (len != 0)
1995 		buf = KERNADDR(&xfer->dmabuf, 0);
1996 
1997 #define C(x,y) ((x) | ((y) << 8))
1998 	switch(C(req->bRequest, req->bmRequestType)) {
1999 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
2000 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
2001 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
2002 		/*
2003 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
2004 		 * for the integrated root hub.
2005 		 */
2006 		break;
2007 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
2008 		if (len > 0) {
2009 			*(u_int8_t *)buf = sc->sc_conf;
2010 			totlen = 1;
2011 		}
2012 		break;
2013 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2014 		DPRINTFN(8,("ehci_root_ctrl_start: wValue=0x%04x\n", value));
2015 		if (len == 0)
2016 			break;
2017 		switch(value >> 8) {
2018 		case UDESC_DEVICE:
2019 			if ((value & 0xff) != 0) {
2020 				err = USBD_IOERROR;
2021 				goto ret;
2022 			}
2023 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
2024 			USETW(ehci_devd.idVendor, sc->sc_id_vendor);
2025 			memcpy(buf, &ehci_devd, l);
2026 			break;
2027 		/*
2028 		 * We can't really operate at another speed, but the spec says
2029 		 * we need this descriptor.
2030 		 */
2031 		case UDESC_DEVICE_QUALIFIER:
2032 			if ((value & 0xff) != 0) {
2033 				err = USBD_IOERROR;
2034 				goto ret;
2035 			}
2036 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
2037 			memcpy(buf, &ehci_odevd, l);
2038 			break;
2039 		/*
2040 		 * We can't really operate at another speed, but the spec says
2041 		 * we need this descriptor.
2042 		 */
2043 		case UDESC_OTHER_SPEED_CONFIGURATION:
2044 		case UDESC_CONFIG:
2045 			if ((value & 0xff) != 0) {
2046 				err = USBD_IOERROR;
2047 				goto ret;
2048 			}
2049 			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
2050 			memcpy(buf, &ehci_confd, l);
2051 			((usb_config_descriptor_t *)buf)->bDescriptorType =
2052 				value >> 8;
2053 			buf = (char *)buf + l;
2054 			len -= l;
2055 			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
2056 			totlen += l;
2057 			memcpy(buf, &ehci_ifcd, l);
2058 			buf = (char *)buf + l;
2059 			len -= l;
2060 			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
2061 			totlen += l;
2062 			memcpy(buf, &ehci_endpd, l);
2063 			break;
2064 		case UDESC_STRING:
2065 #define sd ((usb_string_descriptor_t *)buf)
2066 			switch (value & 0xff) {
2067 			case 0: /* Language table */
2068 				totlen = usb_makelangtbl(sd, len);
2069 				break;
2070 			case 1: /* Vendor */
2071 				totlen = usb_makestrdesc(sd, len,
2072 							 sc->sc_vendor);
2073 				break;
2074 			case 2: /* Product */
2075 				totlen = usb_makestrdesc(sd, len,
2076 							 "EHCI root hub");
2077 				break;
2078 			}
2079 #undef sd
2080 			break;
2081 		default:
2082 			err = USBD_IOERROR;
2083 			goto ret;
2084 		}
2085 		break;
2086 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
2087 		if (len > 0) {
2088 			*(u_int8_t *)buf = 0;
2089 			totlen = 1;
2090 		}
2091 		break;
2092 	case C(UR_GET_STATUS, UT_READ_DEVICE):
2093 		if (len > 1) {
2094 			USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
2095 			totlen = 2;
2096 		}
2097 		break;
2098 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
2099 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
2100 		if (len > 1) {
2101 			USETW(((usb_status_t *)buf)->wStatus, 0);
2102 			totlen = 2;
2103 		}
2104 		break;
2105 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
2106 		if (value >= USB_MAX_DEVICES) {
2107 			err = USBD_IOERROR;
2108 			goto ret;
2109 		}
2110 		sc->sc_addr = value;
2111 		break;
2112 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
2113 		if (value != 0 && value != 1) {
2114 			err = USBD_IOERROR;
2115 			goto ret;
2116 		}
2117 		sc->sc_conf = value;
2118 		break;
2119 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
2120 		break;
2121 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
2122 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
2123 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
2124 		err = USBD_IOERROR;
2125 		goto ret;
2126 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
2127 		break;
2128 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
2129 		break;
2130 	/* Hub requests */
2131 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2132 		break;
2133 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2134 		DPRINTFN(4, ("ehci_root_ctrl_start: UR_CLEAR_PORT_FEATURE "
2135 			     "port=%d feature=%d\n",
2136 			     index, value));
2137 		if (index < 1 || index > sc->sc_noport) {
2138 			err = USBD_IOERROR;
2139 			goto ret;
2140 		}
2141 		port = EHCI_PORTSC(index);
2142 		v = EOREAD4(sc, port);
2143 		DPRINTFN(4, ("ehci_root_ctrl_start: portsc=0x%08x\n", v));
2144 		v &= ~EHCI_PS_CLEAR;
2145 		switch(value) {
2146 		case UHF_PORT_ENABLE:
2147 			EOWRITE4(sc, port, v &~ EHCI_PS_PE);
2148 			break;
2149 		case UHF_PORT_SUSPEND:
2150 			if (!(v & EHCI_PS_SUSP)) /* not suspended */
2151 				break;
2152 			v &= ~EHCI_PS_SUSP;
2153 			EOWRITE4(sc, port, v | EHCI_PS_FPR);
2154 			/* see USB2 spec ch. 7.1.7.7 */
2155 			usb_delay_ms(&sc->sc_bus, 20);
2156 			EOWRITE4(sc, port, v);
2157 			usb_delay_ms(&sc->sc_bus, 2);
2158 #ifdef DEBUG
2159 			v = EOREAD4(sc, port);
2160 			if (v & (EHCI_PS_FPR | EHCI_PS_SUSP))
2161 				printf("ehci: resume failed: %x\n", v);
2162 #endif
2163 			break;
2164 		case UHF_PORT_POWER:
2165 			if (sc->sc_hasppc)
2166 				EOWRITE4(sc, port, v &~ EHCI_PS_PP);
2167 			break;
2168 		case UHF_PORT_TEST:
2169 			DPRINTFN(2,("ehci_root_ctrl_start: clear port test "
2170 				    "%d\n", index));
2171 			break;
2172 		case UHF_PORT_INDICATOR:
2173 			DPRINTFN(2,("ehci_root_ctrl_start: clear port ind "
2174 				    "%d\n", index));
2175 			EOWRITE4(sc, port, v &~ EHCI_PS_PIC);
2176 			break;
2177 		case UHF_C_PORT_CONNECTION:
2178 			EOWRITE4(sc, port, v | EHCI_PS_CSC);
2179 			break;
2180 		case UHF_C_PORT_ENABLE:
2181 			EOWRITE4(sc, port, v | EHCI_PS_PEC);
2182 			break;
2183 		case UHF_C_PORT_SUSPEND:
2184 			/* how? */
2185 			break;
2186 		case UHF_C_PORT_OVER_CURRENT:
2187 			EOWRITE4(sc, port, v | EHCI_PS_OCC);
2188 			break;
2189 		case UHF_C_PORT_RESET:
2190 			sc->sc_isreset[index] = 0;
2191 			break;
2192 		default:
2193 			err = USBD_IOERROR;
2194 			goto ret;
2195 		}
2196 #if 0
2197 		switch(value) {
2198 		case UHF_C_PORT_CONNECTION:
2199 		case UHF_C_PORT_ENABLE:
2200 		case UHF_C_PORT_SUSPEND:
2201 		case UHF_C_PORT_OVER_CURRENT:
2202 		case UHF_C_PORT_RESET:
2203 		default:
2204 			break;
2205 		}
2206 #endif
2207 		break;
2208 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2209 		if (len == 0)
2210 			break;
2211 		if ((value & 0xff) != 0) {
2212 			err = USBD_IOERROR;
2213 			goto ret;
2214 		}
2215 		hubd = ehci_hubd;
2216 		hubd.bNbrPorts = sc->sc_noport;
2217 		v = EOREAD4(sc, EHCI_HCSPARAMS);
2218 		USETW(hubd.wHubCharacteristics,
2219 		    EHCI_HCS_PPC(v) ? UHD_PWR_INDIVIDUAL : UHD_PWR_NO_SWITCH |
2220 		    EHCI_HCS_P_INDICATOR(EREAD4(sc, EHCI_HCSPARAMS))
2221 		        ? UHD_PORT_IND : 0);
2222 		hubd.bPwrOn2PwrGood = 200; /* XXX can't find out? */
2223 		for (i = 0, l = sc->sc_noport; l > 0; i++, l -= 8, v >>= 8)
2224 			hubd.DeviceRemovable[i++] = 0; /* XXX can't find out? */
2225 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
2226 		l = min(len, hubd.bDescLength);
2227 		totlen = l;
2228 		memcpy(buf, &hubd, l);
2229 		break;
2230 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2231 		if (len != 4) {
2232 			err = USBD_IOERROR;
2233 			goto ret;
2234 		}
2235 		memset(buf, 0, len); /* ? XXX */
2236 		totlen = len;
2237 		break;
2238 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2239 		DPRINTFN(8,("ehci_root_ctrl_start: get port status i=%d\n",
2240 			    index));
2241 		if (index < 1 || index > sc->sc_noport) {
2242 			err = USBD_IOERROR;
2243 			goto ret;
2244 		}
2245 		if (len != 4) {
2246 			err = USBD_IOERROR;
2247 			goto ret;
2248 		}
2249 		v = EOREAD4(sc, EHCI_PORTSC(index));
2250 		DPRINTFN(8,("ehci_root_ctrl_start: port status=0x%04x\n",
2251 			    v));
2252 		i = UPS_HIGH_SPEED;
2253 		if (v & EHCI_PS_CS)	i |= UPS_CURRENT_CONNECT_STATUS;
2254 		if (v & EHCI_PS_PE)	i |= UPS_PORT_ENABLED;
2255 		if (v & EHCI_PS_SUSP)	i |= UPS_SUSPEND;
2256 		if (v & EHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
2257 		if (v & EHCI_PS_PR)	i |= UPS_RESET;
2258 		if (v & EHCI_PS_PP)	i |= UPS_PORT_POWER;
2259 		USETW(ps.wPortStatus, i);
2260 		i = 0;
2261 		if (v & EHCI_PS_CSC)	i |= UPS_C_CONNECT_STATUS;
2262 		if (v & EHCI_PS_PEC)	i |= UPS_C_PORT_ENABLED;
2263 		if (v & EHCI_PS_OCC)	i |= UPS_C_OVERCURRENT_INDICATOR;
2264 		if (sc->sc_isreset[index]) i |= UPS_C_PORT_RESET;
2265 		USETW(ps.wPortChange, i);
2266 		l = min(len, sizeof ps);
2267 		memcpy(buf, &ps, l);
2268 		totlen = l;
2269 		break;
2270 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2271 		err = USBD_IOERROR;
2272 		goto ret;
2273 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2274 		break;
2275 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2276 		if (index < 1 || index > sc->sc_noport) {
2277 			err = USBD_IOERROR;
2278 			goto ret;
2279 		}
2280 		port = EHCI_PORTSC(index);
2281 		v = EOREAD4(sc, port);
2282 		DPRINTFN(4, ("ehci_root_ctrl_start: portsc=0x%08x\n", v));
2283 		v &= ~EHCI_PS_CLEAR;
2284 		switch(value) {
2285 		case UHF_PORT_ENABLE:
2286 			EOWRITE4(sc, port, v | EHCI_PS_PE);
2287 			break;
2288 		case UHF_PORT_SUSPEND:
2289 			EOWRITE4(sc, port, v | EHCI_PS_SUSP);
2290 			break;
2291 		case UHF_PORT_RESET:
2292 			DPRINTFN(5,("ehci_root_ctrl_start: reset port %d\n",
2293 				    index));
2294 			if (EHCI_PS_IS_LOWSPEED(v)) {
2295 				/* Low speed device, give up ownership. */
2296 				ehci_disown(sc, index, 1);
2297 				break;
2298 			}
2299 			/* Start reset sequence. */
2300 			v &= ~ (EHCI_PS_PE | EHCI_PS_PR);
2301 			EOWRITE4(sc, port, v | EHCI_PS_PR);
2302 			/* Wait for reset to complete. */
2303 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
2304 			if (sc->sc_dying) {
2305 				err = USBD_IOERROR;
2306 				goto ret;
2307 			}
2308 			/* Terminate reset sequence. */
2309 			EOWRITE4(sc, port, v);
2310 			/* Wait for HC to complete reset. */
2311 			usb_delay_ms(&sc->sc_bus, EHCI_PORT_RESET_COMPLETE);
2312 			if (sc->sc_dying) {
2313 				err = USBD_IOERROR;
2314 				goto ret;
2315 			}
2316 			v = EOREAD4(sc, port);
2317 			DPRINTF(("ehci after reset, status=0x%08x\n", v));
2318 			if (v & EHCI_PS_PR) {
2319 				printf("%s: port reset timeout\n",
2320 				       device_xname(sc->sc_dev));
2321 				return (USBD_TIMEOUT);
2322 			}
2323 			if (!(v & EHCI_PS_PE)) {
2324 				/* Not a high speed device, give up ownership.*/
2325 				ehci_disown(sc, index, 0);
2326 				break;
2327 			}
2328 			sc->sc_isreset[index] = 1;
2329 			DPRINTF(("ehci port %d reset, status = 0x%08x\n",
2330 				 index, v));
2331 			break;
2332 		case UHF_PORT_POWER:
2333 			DPRINTFN(2,("ehci_root_ctrl_start: set port power "
2334 				    "%d (has PPC = %d)\n", index,
2335 				    sc->sc_hasppc));
2336 			if (sc->sc_hasppc)
2337 				EOWRITE4(sc, port, v | EHCI_PS_PP);
2338 			break;
2339 		case UHF_PORT_TEST:
2340 			DPRINTFN(2,("ehci_root_ctrl_start: set port test "
2341 				    "%d\n", index));
2342 			break;
2343 		case UHF_PORT_INDICATOR:
2344 			DPRINTFN(2,("ehci_root_ctrl_start: set port ind "
2345 				    "%d\n", index));
2346 			EOWRITE4(sc, port, v | EHCI_PS_PIC);
2347 			break;
2348 		default:
2349 			err = USBD_IOERROR;
2350 			goto ret;
2351 		}
2352 		break;
2353 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
2354 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
2355 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
2356 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
2357 		break;
2358 	default:
2359 		err = USBD_IOERROR;
2360 		goto ret;
2361 	}
2362 	xfer->actlen = totlen;
2363 	err = USBD_NORMAL_COMPLETION;
2364  ret:
2365 	xfer->status = err;
2366 	s = splusb();
2367 	usb_transfer_complete(xfer);
2368 	splx(s);
2369 	return (USBD_IN_PROGRESS);
2370 }
2371 
2372 void
2373 ehci_disown(ehci_softc_t *sc, int index, int lowspeed)
2374 {
2375 	int port;
2376 	u_int32_t v;
2377 
2378 	DPRINTF(("ehci_disown: index=%d lowspeed=%d\n", index, lowspeed));
2379 #ifdef DIAGNOSTIC
2380 	if (sc->sc_npcomp != 0) {
2381 		int i = (index-1) / sc->sc_npcomp;
2382 		if (i >= sc->sc_ncomp)
2383 			printf("%s: strange port\n",
2384 			       device_xname(sc->sc_dev));
2385 		else
2386 			printf("%s: handing over %s speed device on "
2387 			       "port %d to %s\n",
2388 			       device_xname(sc->sc_dev),
2389 			       lowspeed ? "low" : "full",
2390 			       index, device_xname(sc->sc_comps[i]));
2391 	} else {
2392 		printf("%s: npcomp == 0\n", device_xname(sc->sc_dev));
2393 	}
2394 #endif
2395 	port = EHCI_PORTSC(index);
2396 	v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
2397 	EOWRITE4(sc, port, v | EHCI_PS_PO);
2398 }
2399 
2400 /* Abort a root control request. */
2401 Static void
2402 ehci_root_ctrl_abort(usbd_xfer_handle xfer)
2403 {
2404 	/* Nothing to do, all transfers are synchronous. */
2405 }
2406 
2407 /* Close the root pipe. */
2408 Static void
2409 ehci_root_ctrl_close(usbd_pipe_handle pipe)
2410 {
2411 	DPRINTF(("ehci_root_ctrl_close\n"));
2412 	/* Nothing to do. */
2413 }
2414 
2415 void
2416 ehci_root_intr_done(usbd_xfer_handle xfer)
2417 {
2418 	xfer->hcpriv = NULL;
2419 }
2420 
2421 Static usbd_status
2422 ehci_root_intr_transfer(usbd_xfer_handle xfer)
2423 {
2424 	usbd_status err;
2425 
2426 	/* Insert last in queue. */
2427 	err = usb_insert_transfer(xfer);
2428 	if (err)
2429 		return (err);
2430 
2431 	/* Pipe isn't running, start first */
2432 	return (ehci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2433 }
2434 
2435 Static usbd_status
2436 ehci_root_intr_start(usbd_xfer_handle xfer)
2437 {
2438 	usbd_pipe_handle pipe = xfer->pipe;
2439 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2440 
2441 	if (sc->sc_dying)
2442 		return (USBD_IOERROR);
2443 
2444 	sc->sc_intrxfer = xfer;
2445 
2446 	return (USBD_IN_PROGRESS);
2447 }
2448 
2449 /* Abort a root interrupt request. */
2450 Static void
2451 ehci_root_intr_abort(usbd_xfer_handle xfer)
2452 {
2453 	int s;
2454 
2455 	if (xfer->pipe->intrxfer == xfer) {
2456 		DPRINTF(("ehci_root_intr_abort: remove\n"));
2457 		xfer->pipe->intrxfer = NULL;
2458 	}
2459 	xfer->status = USBD_CANCELLED;
2460 	s = splusb();
2461 	usb_transfer_complete(xfer);
2462 	splx(s);
2463 }
2464 
2465 /* Close the root pipe. */
2466 Static void
2467 ehci_root_intr_close(usbd_pipe_handle pipe)
2468 {
2469 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2470 
2471 	DPRINTF(("ehci_root_intr_close\n"));
2472 
2473 	sc->sc_intrxfer = NULL;
2474 }
2475 
2476 void
2477 ehci_root_ctrl_done(usbd_xfer_handle xfer)
2478 {
2479 	xfer->hcpriv = NULL;
2480 }
2481 
2482 /************************/
2483 
2484 ehci_soft_qh_t *
2485 ehci_alloc_sqh(ehci_softc_t *sc)
2486 {
2487 	ehci_soft_qh_t *sqh;
2488 	usbd_status err;
2489 	int i, offs;
2490 	usb_dma_t dma;
2491 
2492 	if (sc->sc_freeqhs == NULL) {
2493 		DPRINTFN(2, ("ehci_alloc_sqh: allocating chunk\n"));
2494 		err = usb_allocmem(&sc->sc_bus, EHCI_SQH_SIZE * EHCI_SQH_CHUNK,
2495 			  EHCI_PAGE_SIZE, &dma);
2496 #ifdef EHCI_DEBUG
2497 		if (err)
2498 			printf("ehci_alloc_sqh: usb_allocmem()=%d\n", err);
2499 #endif
2500 		if (err)
2501 			return (NULL);
2502 		for(i = 0; i < EHCI_SQH_CHUNK; i++) {
2503 			offs = i * EHCI_SQH_SIZE;
2504 			sqh = KERNADDR(&dma, offs);
2505 			sqh->physaddr = DMAADDR(&dma, offs);
2506 			sqh->dma = dma;
2507 			sqh->offs = offs;
2508 			sqh->next = sc->sc_freeqhs;
2509 			sc->sc_freeqhs = sqh;
2510 		}
2511 	}
2512 	sqh = sc->sc_freeqhs;
2513 	sc->sc_freeqhs = sqh->next;
2514 	memset(&sqh->qh, 0, sizeof(ehci_qh_t));
2515 	sqh->next = NULL;
2516 	return (sqh);
2517 }
2518 
2519 void
2520 ehci_free_sqh(ehci_softc_t *sc, ehci_soft_qh_t *sqh)
2521 {
2522 	sqh->next = sc->sc_freeqhs;
2523 	sc->sc_freeqhs = sqh;
2524 }
2525 
2526 ehci_soft_qtd_t *
2527 ehci_alloc_sqtd(ehci_softc_t *sc)
2528 {
2529 	ehci_soft_qtd_t *sqtd;
2530 	usbd_status err;
2531 	int i, offs;
2532 	usb_dma_t dma;
2533 	int s;
2534 
2535 	if (sc->sc_freeqtds == NULL) {
2536 		DPRINTFN(2, ("ehci_alloc_sqtd: allocating chunk\n"));
2537 		err = usb_allocmem(&sc->sc_bus, EHCI_SQTD_SIZE*EHCI_SQTD_CHUNK,
2538 			  EHCI_PAGE_SIZE, &dma);
2539 #ifdef EHCI_DEBUG
2540 		if (err)
2541 			printf("ehci_alloc_sqtd: usb_allocmem()=%d\n", err);
2542 #endif
2543 		if (err)
2544 			return (NULL);
2545 		s = splusb();
2546 		for(i = 0; i < EHCI_SQTD_CHUNK; i++) {
2547 			offs = i * EHCI_SQTD_SIZE;
2548 			sqtd = KERNADDR(&dma, offs);
2549 			sqtd->physaddr = DMAADDR(&dma, offs);
2550 			sqtd->dma = dma;
2551 			sqtd->offs = offs;
2552 			sqtd->nextqtd = sc->sc_freeqtds;
2553 			sc->sc_freeqtds = sqtd;
2554 		}
2555 		splx(s);
2556 	}
2557 
2558 	s = splusb();
2559 	sqtd = sc->sc_freeqtds;
2560 	sc->sc_freeqtds = sqtd->nextqtd;
2561 	memset(&sqtd->qtd, 0, sizeof(ehci_qtd_t));
2562 	sqtd->nextqtd = NULL;
2563 	sqtd->xfer = NULL;
2564 	splx(s);
2565 
2566 	return (sqtd);
2567 }
2568 
2569 void
2570 ehci_free_sqtd(ehci_softc_t *sc, ehci_soft_qtd_t *sqtd)
2571 {
2572 	int s;
2573 
2574 	s = splusb();
2575 	sqtd->nextqtd = sc->sc_freeqtds;
2576 	sc->sc_freeqtds = sqtd;
2577 	splx(s);
2578 }
2579 
2580 usbd_status
2581 ehci_alloc_sqtd_chain(struct ehci_pipe *epipe, ehci_softc_t *sc,
2582 		     int alen, int rd, usbd_xfer_handle xfer,
2583 		     ehci_soft_qtd_t **sp, ehci_soft_qtd_t **ep)
2584 {
2585 	ehci_soft_qtd_t *next, *cur;
2586 	ehci_physaddr_t dataphys, dataphyspage, dataphyslastpage, nextphys;
2587 	u_int32_t qtdstatus;
2588 	int len, curlen, mps;
2589 	int i, tog;
2590 	usb_dma_t *dma = &xfer->dmabuf;
2591 	u_int16_t flags = xfer->flags;
2592 
2593 	DPRINTFN(alen<4*4096,("ehci_alloc_sqtd_chain: start len=%d\n", alen));
2594 
2595 	len = alen;
2596 	dataphys = DMAADDR(dma, 0);
2597 	dataphyslastpage = EHCI_PAGE(dataphys + len - 1);
2598 	qtdstatus = EHCI_QTD_ACTIVE |
2599 	    EHCI_QTD_SET_PID(rd ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT) |
2600 	    EHCI_QTD_SET_CERR(3)
2601 	    /* IOC set below */
2602 	    /* BYTES set below */
2603 	    ;
2604 	mps = UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize);
2605 	tog = epipe->nexttoggle;
2606 	qtdstatus |= EHCI_QTD_SET_TOGGLE(tog);
2607 
2608 	cur = ehci_alloc_sqtd(sc);
2609 	*sp = cur;
2610 	if (cur == NULL)
2611 		goto nomem;
2612 
2613 	usb_syncmem(dma, 0, alen,
2614 	    rd ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
2615 	for (;;) {
2616 		dataphyspage = EHCI_PAGE(dataphys);
2617 		/* The EHCI hardware can handle at most 5 pages. */
2618 		if (dataphyslastpage - dataphyspage <
2619 		    EHCI_QTD_NBUFFERS * EHCI_PAGE_SIZE) {
2620 			/* we can handle it in this QTD */
2621 			curlen = len;
2622 		} else {
2623 			/* must use multiple TDs, fill as much as possible. */
2624 			curlen = EHCI_QTD_NBUFFERS * EHCI_PAGE_SIZE -
2625 				 EHCI_PAGE_OFFSET(dataphys);
2626 #ifdef DIAGNOSTIC
2627 			if (curlen > len) {
2628 				printf("ehci_alloc_sqtd_chain: curlen=0x%x "
2629 				       "len=0x%x offs=0x%x\n", curlen, len,
2630 				       EHCI_PAGE_OFFSET(dataphys));
2631 				printf("lastpage=0x%x page=0x%x phys=0x%x\n",
2632 				       dataphyslastpage, dataphyspage,
2633 				       dataphys);
2634 				curlen = len;
2635 			}
2636 #endif
2637 			/* the length must be a multiple of the max size */
2638 			curlen -= curlen % mps;
2639 			DPRINTFN(1,("ehci_alloc_sqtd_chain: multiple QTDs, "
2640 				    "curlen=%d\n", curlen));
2641 #ifdef DIAGNOSTIC
2642 			if (curlen == 0)
2643 				panic("ehci_alloc_sqtd_chain: curlen == 0");
2644 #endif
2645 		}
2646 		DPRINTFN(4,("ehci_alloc_sqtd_chain: dataphys=0x%08x "
2647 			    "dataphyslastpage=0x%08x len=%d curlen=%d\n",
2648 			    dataphys, dataphyslastpage,
2649 			    len, curlen));
2650 		len -= curlen;
2651 
2652 		/*
2653 		 * Allocate another transfer if there's more data left,
2654 		 * or if force last short transfer flag is set and we're
2655 		 * allocating a multiple of the max packet size.
2656 		 */
2657 		if (len != 0 ||
2658 		    ((curlen % mps) == 0 && !rd && curlen != 0 &&
2659 		     (flags & USBD_FORCE_SHORT_XFER))) {
2660 			next = ehci_alloc_sqtd(sc);
2661 			if (next == NULL)
2662 				goto nomem;
2663 			nextphys = htole32(next->physaddr);
2664 		} else {
2665 			next = NULL;
2666 			nextphys = EHCI_NULL;
2667 		}
2668 
2669 		for (i = 0; i * EHCI_PAGE_SIZE <
2670 		            curlen + EHCI_PAGE_OFFSET(dataphys); i++) {
2671 			ehci_physaddr_t a = dataphys + i * EHCI_PAGE_SIZE;
2672 			if (i != 0) /* use offset only in first buffer */
2673 				a = EHCI_PAGE(a);
2674 			cur->qtd.qtd_buffer[i] = htole32(a);
2675 			cur->qtd.qtd_buffer_hi[i] = 0;
2676 #ifdef DIAGNOSTIC
2677 			if (i >= EHCI_QTD_NBUFFERS) {
2678 				printf("ehci_alloc_sqtd_chain: i=%d\n", i);
2679 				goto nomem;
2680 			}
2681 #endif
2682 		}
2683 		cur->nextqtd = next;
2684 		cur->qtd.qtd_next = cur->qtd.qtd_altnext = nextphys;
2685 		cur->qtd.qtd_status =
2686 		    htole32(qtdstatus | EHCI_QTD_SET_BYTES(curlen));
2687 		cur->xfer = xfer;
2688 		cur->len = curlen;
2689 
2690 		DPRINTFN(10,("ehci_alloc_sqtd_chain: cbp=0x%08x end=0x%08x\n",
2691 			    dataphys, dataphys + curlen));
2692 		/* adjust the toggle based on the number of packets in this
2693 		   qtd */
2694 		if (((curlen + mps - 1) / mps) & 1) {
2695 			tog ^= 1;
2696 			qtdstatus ^= EHCI_QTD_TOGGLE_MASK;
2697 		}
2698 		if (next == NULL)
2699 			break;
2700 		usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
2701 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2702 		DPRINTFN(10,("ehci_alloc_sqtd_chain: extend chain\n"));
2703 		dataphys += curlen;
2704 		cur = next;
2705 	}
2706 	cur->qtd.qtd_status |= htole32(EHCI_QTD_IOC);
2707 	usb_syncmem(&cur->dma, cur->offs, sizeof(cur->qtd),
2708 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2709 	*ep = cur;
2710 	epipe->nexttoggle = tog;
2711 
2712 	DPRINTFN(10,("ehci_alloc_sqtd_chain: return sqtd=%p sqtdend=%p\n",
2713 		     *sp, *ep));
2714 
2715 	return (USBD_NORMAL_COMPLETION);
2716 
2717  nomem:
2718 	/* XXX free chain */
2719 	DPRINTFN(-1,("ehci_alloc_sqtd_chain: no memory\n"));
2720 	return (USBD_NOMEM);
2721 }
2722 
2723 Static void
2724 ehci_free_sqtd_chain(ehci_softc_t *sc, ehci_soft_qtd_t *sqtd,
2725 		    ehci_soft_qtd_t *sqtdend)
2726 {
2727 	ehci_soft_qtd_t *p;
2728 	int i;
2729 
2730 	DPRINTFN(10,("ehci_free_sqtd_chain: sqtd=%p sqtdend=%p\n",
2731 		     sqtd, sqtdend));
2732 
2733 	for (i = 0; sqtd != sqtdend; sqtd = p, i++) {
2734 		p = sqtd->nextqtd;
2735 		ehci_free_sqtd(sc, sqtd);
2736 	}
2737 }
2738 
2739 ehci_soft_itd_t *
2740 ehci_alloc_itd(ehci_softc_t *sc)
2741 {
2742 	struct ehci_soft_itd *itd, *freeitd;
2743 	usbd_status err;
2744 	int i, s, offs, frindex, previndex;
2745 	usb_dma_t dma;
2746 
2747 	s = splusb();
2748 
2749 	/* Find an itd that wasn't freed this frame or last frame. This can
2750 	 * discard itds that were freed before frindex wrapped around
2751 	 * XXX - can this lead to thrashing? Could fix by enabling wrap-around
2752 	 *       interrupt and fiddling with list when that happens */
2753 	frindex = (EOREAD4(sc, EHCI_FRINDEX) + 1) >> 3;
2754 	previndex = (frindex != 0) ? frindex - 1 : sc->sc_flsize;
2755 
2756 	freeitd = NULL;
2757 	LIST_FOREACH(itd, &sc->sc_freeitds, u.free_list) {
2758 		if (itd == NULL)
2759 			break;
2760 		if (itd->slot != frindex && itd->slot != previndex) {
2761 			freeitd = itd;
2762 			break;
2763 		}
2764 	}
2765 
2766 	if (freeitd == NULL) {
2767 		DPRINTFN(2, ("ehci_alloc_itd allocating chunk\n"));
2768 		err = usb_allocmem(&sc->sc_bus, EHCI_ITD_SIZE * EHCI_ITD_CHUNK,
2769 				EHCI_PAGE_SIZE, &dma);
2770 
2771 		if (err) {
2772 			DPRINTF(("ehci_alloc_itd, alloc returned %d\n", err));
2773 			return NULL;
2774 		}
2775 
2776 		for (i = 0; i < EHCI_ITD_CHUNK; i++) {
2777 			offs = i * EHCI_ITD_SIZE;
2778 			itd = KERNADDR(&dma, offs);
2779 			itd->physaddr = DMAADDR(&dma, offs);
2780 	 		itd->dma = dma;
2781 			itd->offs = offs;
2782 			LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
2783 		}
2784 		freeitd = LIST_FIRST(&sc->sc_freeitds);
2785 	}
2786 
2787 	itd = freeitd;
2788 	LIST_REMOVE(itd, u.free_list);
2789 	memset(&itd->itd, 0, sizeof(ehci_itd_t));
2790 	usb_syncmem(&itd->dma, itd->offs + offsetof(ehci_itd_t, itd_next),
2791                     sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE |
2792                     BUS_DMASYNC_PREREAD);
2793 
2794 	itd->u.frame_list.next = NULL;
2795 	itd->u.frame_list.prev = NULL;
2796 	itd->xfer_next = NULL;
2797 	itd->slot = 0;
2798 	splx(s);
2799 
2800 	return itd;
2801 }
2802 
2803 void
2804 ehci_free_itd(ehci_softc_t *sc, ehci_soft_itd_t *itd)
2805 {
2806 	int s;
2807 
2808 	s = splusb();
2809 	LIST_INSERT_HEAD(&sc->sc_freeitds, itd, u.free_list);
2810 	splx(s);
2811 }
2812 
2813 
2814 
2815 /****************/
2816 
2817 /*
2818  * Close a reqular pipe.
2819  * Assumes that there are no pending transactions.
2820  */
2821 void
2822 ehci_close_pipe(usbd_pipe_handle pipe, ehci_soft_qh_t *head)
2823 {
2824 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
2825 	ehci_softc_t *sc = pipe->device->bus->hci_private;
2826 	ehci_soft_qh_t *sqh = epipe->sqh;
2827 	int s;
2828 
2829 	s = splusb();
2830 	ehci_rem_qh(sc, sqh, head);
2831 	splx(s);
2832 	ehci_free_sqh(sc, epipe->sqh);
2833 }
2834 
2835 /*
2836  * Abort a device request.
2837  * If this routine is called at splusb() it guarantees that the request
2838  * will be removed from the hardware scheduling and that the callback
2839  * for it will be called with USBD_CANCELLED status.
2840  * It's impossible to guarantee that the requested transfer will not
2841  * have happened since the hardware runs concurrently.
2842  * If the transaction has already happened we rely on the ordinary
2843  * interrupt processing to process it.
2844  * XXX This is most probably wrong.
2845  */
2846 void
2847 ehci_abort_xfer(usbd_xfer_handle xfer, usbd_status status)
2848 {
2849 #define exfer EXFER(xfer)
2850 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
2851 	ehci_softc_t *sc = epipe->pipe.device->bus->hci_private;
2852 	ehci_soft_qh_t *sqh = epipe->sqh;
2853 	ehci_soft_qtd_t *sqtd;
2854 	ehci_physaddr_t cur;
2855 	u_int32_t qhstatus;
2856 	int s;
2857 	int hit;
2858 	int wake;
2859 
2860 	DPRINTF(("ehci_abort_xfer: xfer=%p pipe=%p\n", xfer, epipe));
2861 
2862 	if (sc->sc_dying) {
2863 		/* If we're dying, just do the software part. */
2864 		s = splusb();
2865 		xfer->status = status;	/* make software ignore it */
2866                 callout_stop(&(xfer->timeout_handle));
2867 		usb_transfer_complete(xfer);
2868 		splx(s);
2869 		return;
2870 	}
2871 
2872 	if (xfer->device->bus->intr_context)
2873 		panic("ehci_abort_xfer: not in process context");
2874 
2875 	/*
2876 	 * If an abort is already in progress then just wait for it to
2877 	 * complete and return.
2878 	 */
2879 	if (xfer->hcflags & UXFER_ABORTING) {
2880 		DPRINTFN(2, ("ehci_abort_xfer: already aborting\n"));
2881 #ifdef DIAGNOSTIC
2882 		if (status == USBD_TIMEOUT)
2883 			printf("ehci_abort_xfer: TIMEOUT while aborting\n");
2884 #endif
2885 		/* Override the status which might be USBD_TIMEOUT. */
2886 		xfer->status = status;
2887 		DPRINTFN(2, ("ehci_abort_xfer: waiting for abort to finish\n"));
2888 		xfer->hcflags |= UXFER_ABORTWAIT;
2889 		while (xfer->hcflags & UXFER_ABORTING)
2890 			tsleep(&xfer->hcflags, PZERO, "ehciaw", 0);
2891 		return;
2892 	}
2893 	xfer->hcflags |= UXFER_ABORTING;
2894 
2895 	/*
2896 	 * Step 1: Make interrupt routine and hardware ignore xfer.
2897 	 */
2898 	s = splusb();
2899 	xfer->status = status;	/* make software ignore it */
2900         callout_stop(&(xfer->timeout_handle));
2901 
2902 	usb_syncmem(&sqh->dma,
2903 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
2904 	    sizeof(sqh->qh.qh_qtd.qtd_status),
2905 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
2906 	qhstatus = sqh->qh.qh_qtd.qtd_status;
2907 	sqh->qh.qh_qtd.qtd_status = qhstatus | htole32(EHCI_QTD_HALTED);
2908 	usb_syncmem(&sqh->dma,
2909 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
2910 	    sizeof(sqh->qh.qh_qtd.qtd_status),
2911 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2912 	for (sqtd = exfer->sqtdstart; ; sqtd = sqtd->nextqtd) {
2913 		usb_syncmem(&sqtd->dma,
2914 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
2915 		    sizeof(sqtd->qtd.qtd_status),
2916 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
2917 		sqtd->qtd.qtd_status |= htole32(EHCI_QTD_HALTED);
2918 		usb_syncmem(&sqtd->dma,
2919 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
2920 		    sizeof(sqtd->qtd.qtd_status),
2921 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2922 		if (sqtd == exfer->sqtdend)
2923 			break;
2924 	}
2925 	splx(s);
2926 
2927 	/*
2928 	 * Step 2: Wait until we know hardware has finished any possible
2929 	 * use of the xfer.  Also make sure the soft interrupt routine
2930 	 * has run.
2931 	 */
2932 	ehci_sync_hc(sc);
2933 	s = splusb();
2934 #ifdef USB_USE_SOFTINTR
2935 	sc->sc_softwake = 1;
2936 #endif /* USB_USE_SOFTINTR */
2937 	usb_schedsoftintr(&sc->sc_bus);
2938 #ifdef USB_USE_SOFTINTR
2939 	tsleep(&sc->sc_softwake, PZERO, "ehciab", 0);
2940 #endif /* USB_USE_SOFTINTR */
2941 	splx(s);
2942 
2943 	/*
2944 	 * Step 3: Remove any vestiges of the xfer from the hardware.
2945 	 * The complication here is that the hardware may have executed
2946 	 * beyond the xfer we're trying to abort.  So as we're scanning
2947 	 * the TDs of this xfer we check if the hardware points to
2948 	 * any of them.
2949 	 */
2950 	s = splusb();		/* XXX why? */
2951 
2952 	usb_syncmem(&sqh->dma,
2953 	    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
2954 	    sizeof(sqh->qh.qh_curqtd),
2955 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
2956 	cur = EHCI_LINK_ADDR(le32toh(sqh->qh.qh_curqtd));
2957 	hit = 0;
2958 	for (sqtd = exfer->sqtdstart; ; sqtd = sqtd->nextqtd) {
2959 		hit |= cur == sqtd->physaddr;
2960 		if (sqtd == exfer->sqtdend)
2961 			break;
2962 	}
2963 	sqtd = sqtd->nextqtd;
2964 	/* Zap curqtd register if hardware pointed inside the xfer. */
2965 	if (hit && sqtd != NULL) {
2966 		DPRINTFN(1,("ehci_abort_xfer: cur=0x%08x\n", sqtd->physaddr));
2967 		sqh->qh.qh_curqtd = htole32(sqtd->physaddr); /* unlink qTDs */
2968 		usb_syncmem(&sqh->dma,
2969 		    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
2970 		    sizeof(sqh->qh.qh_curqtd),
2971 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2972 		sqh->qh.qh_qtd.qtd_status = qhstatus;
2973 		usb_syncmem(&sqh->dma,
2974 		    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
2975 		    sizeof(sqh->qh.qh_qtd.qtd_status),
2976 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2977 	} else {
2978 		DPRINTFN(1,("ehci_abort_xfer: no hit\n"));
2979 	}
2980 
2981 	/*
2982 	 * Step 4: Execute callback.
2983 	 */
2984 #ifdef DIAGNOSTIC
2985 	exfer->isdone = 1;
2986 #endif
2987 	wake = xfer->hcflags & UXFER_ABORTWAIT;
2988 	xfer->hcflags &= ~(UXFER_ABORTING | UXFER_ABORTWAIT);
2989 	usb_transfer_complete(xfer);
2990 	if (wake)
2991 		wakeup(&xfer->hcflags);
2992 
2993 	splx(s);
2994 #undef exfer
2995 }
2996 
2997 void
2998 ehci_abort_isoc_xfer(usbd_xfer_handle xfer, usbd_status status)
2999 {
3000 	ehci_isoc_trans_t trans_status;
3001 	struct ehci_pipe *epipe;
3002 	struct ehci_xfer *exfer;
3003 	ehci_softc_t *sc;
3004 	struct ehci_soft_itd *itd;
3005 	int s, i, wake;
3006 
3007 	epipe = (struct ehci_pipe *) xfer->pipe;
3008 	exfer = EXFER(xfer);
3009 	sc = epipe->pipe.device->bus->hci_private;
3010 
3011 	DPRINTF(("ehci_abort_isoc_xfer: xfer %p pipe %p\n", xfer, epipe));
3012 
3013 	if (sc->sc_dying) {
3014 		s = splusb();
3015 		xfer->status = status;
3016                 callout_stop(&(xfer->timeout_handle));
3017 		usb_transfer_complete(xfer);
3018 		splx(s);
3019 		return;
3020 	}
3021 
3022 	if (xfer->hcflags & UXFER_ABORTING) {
3023 		DPRINTFN(2, ("ehci_abort_isoc_xfer: already aborting\n"));
3024 
3025 #ifdef DIAGNOSTIC
3026 		if (status == USBD_TIMEOUT)
3027 			printf("ehci_abort_xfer: TIMEOUT while aborting\n");
3028 #endif
3029 
3030 		xfer->status = status;
3031 		DPRINTFN(2, ("ehci_abort_xfer: waiting for abort to finish\n"));
3032 		xfer->hcflags |= UXFER_ABORTWAIT;
3033 		while (xfer->hcflags & UXFER_ABORTING)
3034 			tsleep(&xfer->hcflags, PZERO, "ehciiaw", 0);
3035 		return;
3036 	}
3037 	xfer->hcflags |= UXFER_ABORTING;
3038 
3039 	xfer->status = status;
3040         callout_stop(&(xfer->timeout_handle));
3041 
3042 	s = splusb();
3043 	for (itd = exfer->itdstart; itd != NULL; itd = itd->xfer_next) {
3044 		usb_syncmem(&itd->dma,
3045 		    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3046 		    sizeof(itd->itd.itd_ctl),
3047 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3048 
3049 		for (i = 0; i < 8; i++) {
3050 			trans_status = le32toh(itd->itd.itd_ctl[i]);
3051 			trans_status &= ~EHCI_ITD_ACTIVE;
3052 			itd->itd.itd_ctl[i] = htole32(trans_status);
3053 		}
3054 
3055 		usb_syncmem(&itd->dma,
3056 		    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3057 		    sizeof(itd->itd.itd_ctl),
3058 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3059 	}
3060 	splx(s);
3061 
3062         s = splusb();
3063 #ifdef USB_USE_SOFTINTR
3064         sc->sc_softwake = 1;
3065 #endif /* USB_USE_SOFTINTR */
3066         usb_schedsoftintr(&sc->sc_bus);
3067 #ifdef USB_USE_SOFTINTR
3068         tsleep(&sc->sc_softwake, PZERO, "ehciab", 0);
3069 #endif /* USB_USE_SOFTINTR */
3070         splx(s);
3071 
3072 #ifdef DIAGNOSTIC
3073 	exfer->isdone = 1;
3074 #endif
3075 	wake = xfer->hcflags & UXFER_ABORTWAIT;
3076 	xfer->hcflags &= ~(UXFER_ABORTING | UXFER_ABORTWAIT);
3077 	usb_transfer_complete(xfer);
3078 	if (wake)
3079 		wakeup(&xfer->hcflags);
3080 
3081 	return;
3082 }
3083 
3084 void
3085 ehci_timeout(void *addr)
3086 {
3087 	struct ehci_xfer *exfer = addr;
3088 	struct ehci_pipe *epipe = (struct ehci_pipe *)exfer->xfer.pipe;
3089 	ehci_softc_t *sc = epipe->pipe.device->bus->hci_private;
3090 
3091 	DPRINTF(("ehci_timeout: exfer=%p\n", exfer));
3092 #ifdef EHCI_DEBUG
3093 	if (ehcidebug > 1)
3094 		usbd_dump_pipe(exfer->xfer.pipe);
3095 #endif
3096 
3097 	if (sc->sc_dying) {
3098 		ehci_abort_xfer(&exfer->xfer, USBD_TIMEOUT);
3099 		return;
3100 	}
3101 
3102 	/* Execute the abort in a process context. */
3103 	usb_init_task(&exfer->abort_task, ehci_timeout_task, addr);
3104 	usb_add_task(exfer->xfer.pipe->device, &exfer->abort_task,
3105 	    USB_TASKQ_HC);
3106 }
3107 
3108 void
3109 ehci_timeout_task(void *addr)
3110 {
3111 	usbd_xfer_handle xfer = addr;
3112 	int s;
3113 
3114 	DPRINTF(("ehci_timeout_task: xfer=%p\n", xfer));
3115 
3116 	s = splusb();
3117 	ehci_abort_xfer(xfer, USBD_TIMEOUT);
3118 	splx(s);
3119 }
3120 
3121 /************************/
3122 
3123 Static usbd_status
3124 ehci_device_ctrl_transfer(usbd_xfer_handle xfer)
3125 {
3126 	usbd_status err;
3127 
3128 	/* Insert last in queue. */
3129 	err = usb_insert_transfer(xfer);
3130 	if (err)
3131 		return (err);
3132 
3133 	/* Pipe isn't running, start first */
3134 	return (ehci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3135 }
3136 
3137 Static usbd_status
3138 ehci_device_ctrl_start(usbd_xfer_handle xfer)
3139 {
3140 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3141 	usbd_status err;
3142 
3143 	if (sc->sc_dying)
3144 		return (USBD_IOERROR);
3145 
3146 #ifdef DIAGNOSTIC
3147 	if (!(xfer->rqflags & URQ_REQUEST)) {
3148 		/* XXX panic */
3149 		printf("ehci_device_ctrl_transfer: not a request\n");
3150 		return (USBD_INVAL);
3151 	}
3152 #endif
3153 
3154 	err = ehci_device_request(xfer);
3155 	if (err)
3156 		return (err);
3157 
3158 	if (sc->sc_bus.use_polling)
3159 		ehci_waitintr(sc, xfer);
3160 	return (USBD_IN_PROGRESS);
3161 }
3162 
3163 void
3164 ehci_device_ctrl_done(usbd_xfer_handle xfer)
3165 {
3166 	struct ehci_xfer *ex = EXFER(xfer);
3167 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3168 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3169 	usb_device_request_t *req = &xfer->request;
3170 	int len = UGETW(req->wLength);
3171 	int rd = req->bmRequestType & UT_READ;
3172 
3173 	DPRINTFN(10,("ehci_ctrl_done: xfer=%p\n", xfer));
3174 
3175 #ifdef DIAGNOSTIC
3176 	if (!(xfer->rqflags & URQ_REQUEST)) {
3177 		panic("ehci_ctrl_done: not a request");
3178 	}
3179 #endif
3180 
3181 	mutex_enter(&sc->sc_intrhead_lock);
3182 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3183 		ehci_del_intr_list(sc, ex);	/* remove from active list */
3184 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3185 		usb_syncmem(&epipe->u.ctl.reqdma, 0, sizeof *req,
3186 		    BUS_DMASYNC_POSTWRITE);
3187 		if (len)
3188 			usb_syncmem(&xfer->dmabuf, 0, len,
3189 			    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3190 	}
3191 	mutex_exit(&sc->sc_intrhead_lock);
3192 
3193 	DPRINTFN(5, ("ehci_ctrl_done: length=%d\n", xfer->actlen));
3194 }
3195 
3196 /* Abort a device control request. */
3197 Static void
3198 ehci_device_ctrl_abort(usbd_xfer_handle xfer)
3199 {
3200 	DPRINTF(("ehci_device_ctrl_abort: xfer=%p\n", xfer));
3201 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3202 }
3203 
3204 /* Close a device control pipe. */
3205 Static void
3206 ehci_device_ctrl_close(usbd_pipe_handle pipe)
3207 {
3208 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3209 	/*struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;*/
3210 
3211 	DPRINTF(("ehci_device_ctrl_close: pipe=%p\n", pipe));
3212 	ehci_close_pipe(pipe, sc->sc_async_head);
3213 }
3214 
3215 usbd_status
3216 ehci_device_request(usbd_xfer_handle xfer)
3217 {
3218 #define exfer EXFER(xfer)
3219 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3220 	usb_device_request_t *req = &xfer->request;
3221 	usbd_device_handle dev = epipe->pipe.device;
3222 	ehci_softc_t *sc = dev->bus->hci_private;
3223 	int addr = dev->address;
3224 	ehci_soft_qtd_t *setup, *stat, *next;
3225 	ehci_soft_qh_t *sqh;
3226 	int isread;
3227 	int len;
3228 	usbd_status err;
3229 	int s;
3230 
3231 	isread = req->bmRequestType & UT_READ;
3232 	len = UGETW(req->wLength);
3233 
3234 	DPRINTFN(3,("ehci_device_request: type=0x%02x, request=0x%02x, "
3235 		    "wValue=0x%04x, wIndex=0x%04x len=%d, addr=%d, endpt=%d\n",
3236 		    req->bmRequestType, req->bRequest, UGETW(req->wValue),
3237 		    UGETW(req->wIndex), len, addr,
3238 		    epipe->pipe.endpoint->edesc->bEndpointAddress));
3239 
3240 	setup = ehci_alloc_sqtd(sc);
3241 	if (setup == NULL) {
3242 		err = USBD_NOMEM;
3243 		goto bad1;
3244 	}
3245 	stat = ehci_alloc_sqtd(sc);
3246 	if (stat == NULL) {
3247 		err = USBD_NOMEM;
3248 		goto bad2;
3249 	}
3250 
3251 	sqh = epipe->sqh;
3252 	epipe->u.ctl.length = len;
3253 
3254 	/* Update device address and length since they may have changed
3255 	   during the setup of the control pipe in usbd_new_device(). */
3256 	/* XXX This only needs to be done once, but it's too early in open. */
3257 	/* XXXX Should not touch ED here! */
3258 	sqh->qh.qh_endp =
3259 	    (sqh->qh.qh_endp & htole32(~(EHCI_QH_ADDRMASK | EHCI_QH_MPLMASK))) |
3260 	    htole32(
3261 	     EHCI_QH_SET_ADDR(addr) |
3262 	     EHCI_QH_SET_MPL(UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize))
3263 	    );
3264 
3265 	/* Set up data transaction */
3266 	if (len != 0) {
3267 		ehci_soft_qtd_t *end;
3268 
3269 		/* Start toggle at 1. */
3270 		epipe->nexttoggle = 1;
3271 		err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer,
3272 			  &next, &end);
3273 		if (err)
3274 			goto bad3;
3275 		end->qtd.qtd_status &= htole32(~EHCI_QTD_IOC);
3276 		end->nextqtd = stat;
3277 		end->qtd.qtd_next =
3278 		end->qtd.qtd_altnext = htole32(stat->physaddr);
3279 		usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
3280 		   BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3281 	} else {
3282 		next = stat;
3283 	}
3284 
3285 	memcpy(KERNADDR(&epipe->u.ctl.reqdma, 0), req, sizeof *req);
3286 	usb_syncmem(&epipe->u.ctl.reqdma, 0, sizeof *req, BUS_DMASYNC_PREWRITE);
3287 
3288 	/* Clear toggle */
3289 	setup->qtd.qtd_status = htole32(
3290 	    EHCI_QTD_ACTIVE |
3291 	    EHCI_QTD_SET_PID(EHCI_QTD_PID_SETUP) |
3292 	    EHCI_QTD_SET_CERR(3) |
3293 	    EHCI_QTD_SET_TOGGLE(0) |
3294 	    EHCI_QTD_SET_BYTES(sizeof *req)
3295 	    );
3296 	setup->qtd.qtd_buffer[0] = htole32(DMAADDR(&epipe->u.ctl.reqdma, 0));
3297 	setup->qtd.qtd_buffer_hi[0] = 0;
3298 	setup->nextqtd = next;
3299 	setup->qtd.qtd_next = setup->qtd.qtd_altnext = htole32(next->physaddr);
3300 	setup->xfer = xfer;
3301 	setup->len = sizeof *req;
3302 	usb_syncmem(&setup->dma, setup->offs, sizeof(setup->qtd),
3303 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3304 
3305 	stat->qtd.qtd_status = htole32(
3306 	    EHCI_QTD_ACTIVE |
3307 	    EHCI_QTD_SET_PID(isread ? EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN) |
3308 	    EHCI_QTD_SET_CERR(3) |
3309 	    EHCI_QTD_SET_TOGGLE(1) |
3310 	    EHCI_QTD_IOC
3311 	    );
3312 	stat->qtd.qtd_buffer[0] = 0; /* XXX not needed? */
3313 	stat->qtd.qtd_buffer_hi[0] = 0; /* XXX not needed? */
3314 	stat->nextqtd = NULL;
3315 	stat->qtd.qtd_next = stat->qtd.qtd_altnext = EHCI_NULL;
3316 	stat->xfer = xfer;
3317 	stat->len = 0;
3318 	usb_syncmem(&stat->dma, stat->offs, sizeof(stat->qtd),
3319 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3320 
3321 #ifdef EHCI_DEBUG
3322 	if (ehcidebug > 5) {
3323 		DPRINTF(("ehci_device_request:\n"));
3324 		ehci_dump_sqh(sqh);
3325 		ehci_dump_sqtds(setup);
3326 	}
3327 #endif
3328 
3329 	exfer->sqtdstart = setup;
3330 	exfer->sqtdend = stat;
3331 #ifdef DIAGNOSTIC
3332 	if (!exfer->isdone) {
3333 		printf("ehci_device_request: not done, exfer=%p\n", exfer);
3334 	}
3335 	exfer->isdone = 0;
3336 #endif
3337 
3338 	/* Insert qTD in QH list. */
3339 	s = splusb();
3340 	ehci_set_qh_qtd(sqh, setup); /* also does usb_syncmem(sqh) */
3341 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3342 		callout_reset(&(xfer->timeout_handle), (mstohz(xfer->timeout)),
3343 		    (ehci_timeout), (xfer));
3344 	}
3345 	mutex_enter(&sc->sc_intrhead_lock);
3346 	ehci_add_intr_list(sc, exfer);
3347 	mutex_exit(&sc->sc_intrhead_lock);
3348 	xfer->status = USBD_IN_PROGRESS;
3349 	splx(s);
3350 
3351 #ifdef EHCI_DEBUG
3352 	if (ehcidebug > 10) {
3353 		DPRINTF(("ehci_device_request: status=%x\n",
3354 			 EOREAD4(sc, EHCI_USBSTS)));
3355 		delay(10000);
3356 		ehci_dump_regs(sc);
3357 		ehci_dump_sqh(sc->sc_async_head);
3358 		ehci_dump_sqh(sqh);
3359 		ehci_dump_sqtds(setup);
3360 	}
3361 #endif
3362 
3363 	return (USBD_NORMAL_COMPLETION);
3364 
3365  bad3:
3366 	ehci_free_sqtd(sc, stat);
3367  bad2:
3368 	ehci_free_sqtd(sc, setup);
3369  bad1:
3370 	DPRINTFN(-1,("ehci_device_request: no memory\n"));
3371 	xfer->status = err;
3372 	usb_transfer_complete(xfer);
3373 	return (err);
3374 #undef exfer
3375 }
3376 
3377 /*
3378  * Some EHCI chips from VIA seem to trigger interrupts before writing back the
3379  * qTD status, or miss signalling occasionally under heavy load.  If the host
3380  * machine is too fast, we we can miss transaction completion - when we scan
3381  * the active list the transaction still seems to be active.  This generally
3382  * exhibits itself as a umass stall that never recovers.
3383  *
3384  * We work around this behaviour by setting up this callback after any softintr
3385  * that completes with transactions still pending, giving us another chance to
3386  * check for completion after the writeback has taken place.
3387  */
3388 void
3389 ehci_intrlist_timeout(void *arg)
3390 {
3391 	ehci_softc_t *sc = arg;
3392 	int s = splusb();
3393 
3394 	DPRINTF(("ehci_intrlist_timeout\n"));
3395 	usb_schedsoftintr(&sc->sc_bus);
3396 
3397 	splx(s);
3398 }
3399 
3400 /************************/
3401 
3402 Static usbd_status
3403 ehci_device_bulk_transfer(usbd_xfer_handle xfer)
3404 {
3405 	usbd_status err;
3406 
3407 	/* Insert last in queue. */
3408 	err = usb_insert_transfer(xfer);
3409 	if (err)
3410 		return (err);
3411 
3412 	/* Pipe isn't running, start first */
3413 	return (ehci_device_bulk_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3414 }
3415 
3416 usbd_status
3417 ehci_device_bulk_start(usbd_xfer_handle xfer)
3418 {
3419 #define exfer EXFER(xfer)
3420 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3421 	usbd_device_handle dev = epipe->pipe.device;
3422 	ehci_softc_t *sc = dev->bus->hci_private;
3423 	ehci_soft_qtd_t *data, *dataend;
3424 	ehci_soft_qh_t *sqh;
3425 	usbd_status err;
3426 	int len, isread, endpt;
3427 	int s;
3428 
3429 	DPRINTFN(2, ("ehci_device_bulk_start: xfer=%p len=%d flags=%d\n",
3430 		     xfer, xfer->length, xfer->flags));
3431 
3432 	if (sc->sc_dying)
3433 		return (USBD_IOERROR);
3434 
3435 #ifdef DIAGNOSTIC
3436 	if (xfer->rqflags & URQ_REQUEST)
3437 		panic("ehci_device_bulk_start: a request");
3438 #endif
3439 
3440 	len = xfer->length;
3441 	endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3442 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3443 	sqh = epipe->sqh;
3444 
3445 	epipe->u.bulk.length = len;
3446 
3447 	err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer, &data,
3448 				   &dataend);
3449 	if (err) {
3450 		DPRINTFN(-1,("ehci_device_bulk_transfer: no memory\n"));
3451 		xfer->status = err;
3452 		usb_transfer_complete(xfer);
3453 		return (err);
3454 	}
3455 
3456 #ifdef EHCI_DEBUG
3457 	if (ehcidebug > 5) {
3458 		DPRINTF(("ehci_device_bulk_start: data(1)\n"));
3459 		ehci_dump_sqh(sqh);
3460 		ehci_dump_sqtds(data);
3461 	}
3462 #endif
3463 
3464 	/* Set up interrupt info. */
3465 	exfer->sqtdstart = data;
3466 	exfer->sqtdend = dataend;
3467 #ifdef DIAGNOSTIC
3468 	if (!exfer->isdone) {
3469 		printf("ehci_device_bulk_start: not done, ex=%p\n", exfer);
3470 	}
3471 	exfer->isdone = 0;
3472 #endif
3473 
3474 	s = splusb();
3475 	ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3476 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3477 		callout_reset(&(xfer->timeout_handle), (mstohz(xfer->timeout)),
3478 		    (ehci_timeout), (xfer));
3479 	}
3480 	mutex_enter(&sc->sc_intrhead_lock);
3481 	ehci_add_intr_list(sc, exfer);
3482 	mutex_exit(&sc->sc_intrhead_lock);
3483 	xfer->status = USBD_IN_PROGRESS;
3484 	splx(s);
3485 
3486 #ifdef EHCI_DEBUG
3487 	if (ehcidebug > 10) {
3488 		DPRINTF(("ehci_device_bulk_start: data(2)\n"));
3489 		delay(10000);
3490 		DPRINTF(("ehci_device_bulk_start: data(3)\n"));
3491 		ehci_dump_regs(sc);
3492 #if 0
3493 		printf("async_head:\n");
3494 		ehci_dump_sqh(sc->sc_async_head);
3495 #endif
3496 		printf("sqh:\n");
3497 		ehci_dump_sqh(sqh);
3498 		ehci_dump_sqtds(data);
3499 	}
3500 #endif
3501 
3502 	if (sc->sc_bus.use_polling)
3503 		ehci_waitintr(sc, xfer);
3504 
3505 	return (USBD_IN_PROGRESS);
3506 #undef exfer
3507 }
3508 
3509 Static void
3510 ehci_device_bulk_abort(usbd_xfer_handle xfer)
3511 {
3512 	DPRINTF(("ehci_device_bulk_abort: xfer=%p\n", xfer));
3513 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3514 }
3515 
3516 /*
3517  * Close a device bulk pipe.
3518  */
3519 Static void
3520 ehci_device_bulk_close(usbd_pipe_handle pipe)
3521 {
3522 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3523 
3524 	DPRINTF(("ehci_device_bulk_close: pipe=%p\n", pipe));
3525 	ehci_close_pipe(pipe, sc->sc_async_head);
3526 }
3527 
3528 void
3529 ehci_device_bulk_done(usbd_xfer_handle xfer)
3530 {
3531 	struct ehci_xfer *ex = EXFER(xfer);
3532 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3533 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3534 	int endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3535 	int rd = UE_GET_DIR(endpt) == UE_DIR_IN;
3536 
3537 	DPRINTFN(10,("ehci_bulk_done: xfer=%p, actlen=%d\n",
3538 		     xfer, xfer->actlen));
3539 
3540 	mutex_enter(&sc->sc_intrhead_lock);
3541 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3542 		ehci_del_intr_list(sc, ex);	/* remove from active list */
3543 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3544 		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
3545 		    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3546 	}
3547 	mutex_exit(&sc->sc_intrhead_lock);
3548 
3549 	DPRINTFN(5, ("ehci_bulk_done: length=%d\n", xfer->actlen));
3550 }
3551 
3552 /************************/
3553 
3554 Static usbd_status
3555 ehci_device_setintr(ehci_softc_t *sc, ehci_soft_qh_t *sqh, int ival)
3556 {
3557 	struct ehci_soft_islot *isp;
3558 	int islot, lev;
3559 
3560 	/* Find a poll rate that is large enough. */
3561 	for (lev = EHCI_IPOLLRATES - 1; lev > 0; lev--)
3562 		if (EHCI_ILEV_IVAL(lev) <= ival)
3563 			break;
3564 
3565 	/* Pick an interrupt slot at the right level. */
3566 	/* XXX could do better than picking at random */
3567 	sc->sc_rand = (sc->sc_rand + 191) % sc->sc_flsize;
3568 	islot = EHCI_IQHIDX(lev, sc->sc_rand);
3569 
3570 	sqh->islot = islot;
3571 	isp = &sc->sc_islots[islot];
3572 	ehci_add_qh(sqh, isp->sqh);
3573 
3574 	return (USBD_NORMAL_COMPLETION);
3575 }
3576 
3577 Static usbd_status
3578 ehci_device_intr_transfer(usbd_xfer_handle xfer)
3579 {
3580 	usbd_status err;
3581 
3582 	/* Insert last in queue. */
3583 	err = usb_insert_transfer(xfer);
3584 	if (err)
3585 		return (err);
3586 
3587 	/*
3588 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
3589 	 * so start it first.
3590 	 */
3591 	return (ehci_device_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3592 }
3593 
3594 Static usbd_status
3595 ehci_device_intr_start(usbd_xfer_handle xfer)
3596 {
3597 #define exfer EXFER(xfer)
3598 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3599 	usbd_device_handle dev = xfer->pipe->device;
3600 	ehci_softc_t *sc = dev->bus->hci_private;
3601 	ehci_soft_qtd_t *data, *dataend;
3602 	ehci_soft_qh_t *sqh;
3603 	usbd_status err;
3604 	int len, isread, endpt;
3605 	int s;
3606 
3607 	DPRINTFN(2, ("ehci_device_intr_start: xfer=%p len=%d flags=%d\n",
3608 	    xfer, xfer->length, xfer->flags));
3609 
3610 	if (sc->sc_dying)
3611 		return (USBD_IOERROR);
3612 
3613 #ifdef DIAGNOSTIC
3614 	if (xfer->rqflags & URQ_REQUEST)
3615 		panic("ehci_device_intr_start: a request");
3616 #endif
3617 
3618 	len = xfer->length;
3619 	endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3620 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3621 	sqh = epipe->sqh;
3622 
3623 	epipe->u.intr.length = len;
3624 
3625 	err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer, &data,
3626 	    &dataend);
3627 	if (err) {
3628 		DPRINTFN(-1, ("ehci_device_intr_start: no memory\n"));
3629 		xfer->status = err;
3630 		usb_transfer_complete(xfer);
3631 		return (err);
3632 	}
3633 
3634 #ifdef EHCI_DEBUG
3635 	if (ehcidebug > 5) {
3636 		DPRINTF(("ehci_device_intr_start: data(1)\n"));
3637 		ehci_dump_sqh(sqh);
3638 		ehci_dump_sqtds(data);
3639 	}
3640 #endif
3641 
3642 	/* Set up interrupt info. */
3643 	exfer->sqtdstart = data;
3644 	exfer->sqtdend = dataend;
3645 #ifdef DIAGNOSTIC
3646 	if (!exfer->isdone) {
3647 		printf("ehci_device_intr_start: not done, ex=%p\n", exfer);
3648 	}
3649 	exfer->isdone = 0;
3650 #endif
3651 
3652 	s = splusb();
3653 	ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3654 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3655                 callout_reset(&(xfer->timeout_handle), (mstohz(xfer->timeout)),
3656 		    (ehci_timeout), (xfer));
3657 	}
3658 	mutex_enter(&sc->sc_intrhead_lock);
3659 	ehci_add_intr_list(sc, exfer);
3660 	mutex_exit(&sc->sc_intrhead_lock);
3661 	xfer->status = USBD_IN_PROGRESS;
3662 	splx(s);
3663 
3664 #ifdef EHCI_DEBUG
3665 	if (ehcidebug > 10) {
3666 		DPRINTF(("ehci_device_intr_start: data(2)\n"));
3667 		delay(10000);
3668 		DPRINTF(("ehci_device_intr_start: data(3)\n"));
3669 		ehci_dump_regs(sc);
3670 		printf("sqh:\n");
3671 		ehci_dump_sqh(sqh);
3672 		ehci_dump_sqtds(data);
3673 	}
3674 #endif
3675 
3676 	if (sc->sc_bus.use_polling)
3677 		ehci_waitintr(sc, xfer);
3678 
3679 	return (USBD_IN_PROGRESS);
3680 #undef exfer
3681 }
3682 
3683 Static void
3684 ehci_device_intr_abort(usbd_xfer_handle xfer)
3685 {
3686 	DPRINTFN(1, ("ehci_device_intr_abort: xfer=%p\n", xfer));
3687 	if (xfer->pipe->intrxfer == xfer) {
3688 		DPRINTFN(1, ("echi_device_intr_abort: remove\n"));
3689 		xfer->pipe->intrxfer = NULL;
3690 	}
3691 	/*
3692 	 * XXX - abort_xfer uses ehci_sync_hc, which syncs via the advance
3693 	 *       async doorbell. That's dependant on the async list, wheras
3694 	 *       intr xfers are periodic, should not use this?
3695 	 */
3696 	ehci_abort_xfer(xfer, USBD_CANCELLED);
3697 }
3698 
3699 Static void
3700 ehci_device_intr_close(usbd_pipe_handle pipe)
3701 {
3702 	ehci_softc_t *sc = pipe->device->bus->hci_private;
3703 	struct ehci_pipe *epipe = (struct ehci_pipe *)pipe;
3704 	struct ehci_soft_islot *isp;
3705 
3706 	isp = &sc->sc_islots[epipe->sqh->islot];
3707 	ehci_close_pipe(pipe, isp->sqh);
3708 }
3709 
3710 Static void
3711 ehci_device_intr_done(usbd_xfer_handle xfer)
3712 {
3713 #define exfer EXFER(xfer)
3714 	struct ehci_xfer *ex = EXFER(xfer);
3715 	ehci_softc_t *sc = xfer->pipe->device->bus->hci_private;
3716 	struct ehci_pipe *epipe = (struct ehci_pipe *)xfer->pipe;
3717 	ehci_soft_qtd_t *data, *dataend;
3718 	ehci_soft_qh_t *sqh;
3719 	usbd_status err;
3720 	int len, isread, endpt, s;
3721 
3722 	DPRINTFN(10, ("ehci_device_intr_done: xfer=%p, actlen=%d\n",
3723 	    xfer, xfer->actlen));
3724 
3725 	mutex_enter(&sc->sc_intrhead_lock);
3726 	if (xfer->pipe->repeat) {
3727 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3728 
3729 		len = epipe->u.intr.length;
3730 		xfer->length = len;
3731 		endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3732 		isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3733 		usb_syncmem(&xfer->dmabuf, 0, len,
3734 		    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3735 		sqh = epipe->sqh;
3736 
3737 		err = ehci_alloc_sqtd_chain(epipe, sc, len, isread, xfer,
3738 		    &data, &dataend);
3739 		if (err) {
3740 			DPRINTFN(-1, ("ehci_device_intr_done: no memory\n"));
3741 			xfer->status = err;
3742 			mutex_exit(&sc->sc_intrhead_lock);
3743 			return;
3744 		}
3745 
3746 		/* Set up interrupt info. */
3747 		exfer->sqtdstart = data;
3748 		exfer->sqtdend = dataend;
3749 #ifdef DIAGNOSTIC
3750 		if (!exfer->isdone) {
3751 			printf("ehci_device_intr_done: not done, ex=%p\n",
3752 			    exfer);
3753 		}
3754 		exfer->isdone = 0;
3755 #endif
3756 
3757 		s = splusb();
3758 		ehci_set_qh_qtd(sqh, data); /* also does usb_syncmem(sqh) */
3759 		if (xfer->timeout && !sc->sc_bus.use_polling) {
3760                         callout_reset(&(xfer->timeout_handle),
3761 			    (mstohz(xfer->timeout)), (ehci_timeout), (xfer));
3762 		}
3763 		splx(s);
3764 
3765 		xfer->status = USBD_IN_PROGRESS;
3766 	} else if (xfer->status != USBD_NOMEM && ehci_active_intr_list(ex)) {
3767 		ehci_del_intr_list(sc, ex); /* remove from active list */
3768 		ehci_free_sqtd_chain(sc, ex->sqtdstart, NULL);
3769 		endpt = epipe->pipe.endpoint->edesc->bEndpointAddress;
3770 		isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3771 		usb_syncmem(&xfer->dmabuf, 0, xfer->length,
3772 		    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3773 	}
3774 	mutex_exit(&sc->sc_intrhead_lock);
3775 #undef exfer
3776 }
3777 
3778 /************************/
3779 
3780 Static usbd_status
3781 ehci_device_isoc_transfer(usbd_xfer_handle xfer)
3782 {
3783 	usbd_status err;
3784 
3785 	err = usb_insert_transfer(xfer);
3786 	if (err && err != USBD_IN_PROGRESS)
3787 		return err;
3788 
3789 	return ehci_device_isoc_start(xfer);
3790 }
3791 
3792 Static usbd_status
3793 ehci_device_isoc_start(usbd_xfer_handle xfer)
3794 {
3795 	struct ehci_pipe *epipe;
3796 	usbd_device_handle dev;
3797 	ehci_softc_t *sc;
3798 	struct ehci_xfer *exfer;
3799 	ehci_soft_itd_t *itd, *prev, *start, *stop;
3800 	usb_dma_t *dma_buf;
3801 	int i, j, k, frames, uframes, ufrperframe;
3802 	int s, trans_count, offs, total_length;
3803 	int frindex;
3804 
3805 	start = NULL;
3806 	prev = NULL;
3807 	itd = NULL;
3808 	trans_count = 0;
3809 	total_length = 0;
3810 	exfer = (struct ehci_xfer *) xfer;
3811 	sc = xfer->pipe->device->bus->hci_private;
3812 	dev = xfer->pipe->device;
3813 	epipe = (struct ehci_pipe *)xfer->pipe;
3814 
3815 	/*
3816 	 * To allow continuous transfers, above we start all transfers
3817 	 * immediately. However, we're still going to get usbd_start_next call
3818 	 * this when another xfer completes. So, check if this is already
3819 	 * in progress or not
3820 	 */
3821 
3822 	if (exfer->itdstart != NULL)
3823 		return USBD_IN_PROGRESS;
3824 
3825 	DPRINTFN(2, ("ehci_device_isoc_start: xfer %p len %d flags %d\n",
3826 			xfer, xfer->length, xfer->flags));
3827 
3828 	if (sc->sc_dying)
3829 		return USBD_IOERROR;
3830 
3831 	/*
3832 	 * To avoid complication, don't allow a request right now that'll span
3833 	 * the entire frame table. To within 4 frames, to allow some leeway
3834 	 * on either side of where the hc currently is.
3835 	 */
3836 	if ((1 << (epipe->pipe.endpoint->edesc->bInterval)) *
3837 			xfer->nframes >= (sc->sc_flsize - 4) * 8) {
3838 		printf("ehci: isoc descriptor requested that spans the entire frametable, too many frames\n");
3839 		return USBD_INVAL;
3840 	}
3841 
3842 #ifdef DIAGNOSTIC
3843 	if (xfer->rqflags & URQ_REQUEST)
3844 		panic("ehci_device_isoc_start: request\n");
3845 
3846 	if (!exfer->isdone)
3847 		printf("ehci_device_isoc_start: not done, ex = %p\n", exfer);
3848 	exfer->isdone = 0;
3849 #endif
3850 
3851 	/*
3852 	 * Step 1: Allocate and initialize itds, how many do we need?
3853 	 * One per transfer if interval >= 8 microframes, fewer if we use
3854 	 * multiple microframes per frame.
3855 	 */
3856 
3857 	i = epipe->pipe.endpoint->edesc->bInterval;
3858 	if (i > 16 || i == 0) {
3859 		/* Spec page 271 says intervals > 16 are invalid */
3860 		DPRINTF(("ehci_device_isoc_start: bInvertal %d invalid\n", i));
3861 		return USBD_INVAL;
3862 	}
3863 
3864 	switch (i) {
3865 	case 1:
3866 		ufrperframe = 8;
3867 		break;
3868 	case 2:
3869 		ufrperframe = 4;
3870 		break;
3871 	case 3:
3872 		ufrperframe = 2;
3873 		break;
3874 	default:
3875 		ufrperframe = 1;
3876 		break;
3877 	}
3878 	frames = (xfer->nframes + (ufrperframe - 1)) / ufrperframe;
3879 	uframes = 8 / ufrperframe;
3880 
3881 	if (frames == 0) {
3882 		DPRINTF(("ehci_device_isoc_start: frames == 0\n"));
3883 		return USBD_INVAL;
3884 	}
3885 
3886 	dma_buf = &xfer->dmabuf;
3887 	offs = 0;
3888 
3889 	for (i = 0; i < frames; i++) {
3890 		int froffs = offs;
3891 		itd = ehci_alloc_itd(sc);
3892 
3893 		if (prev != NULL) {
3894 			prev->itd.itd_next =
3895 			    htole32(itd->physaddr | EHCI_LINK_ITD);
3896 			usb_syncmem(&itd->dma,
3897 			    itd->offs + offsetof(ehci_itd_t, itd_next),
3898                 	    sizeof(itd->itd.itd_next), BUS_DMASYNC_POSTWRITE);
3899 
3900 			prev->xfer_next = itd;
3901 	    	} else {
3902 			start = itd;
3903 		}
3904 
3905 		/*
3906 		 * Step 1.5, initialize uframes
3907 		 */
3908 		for (j = 0; j < 8; j += uframes) {
3909 			/* Calculate which page in the list this starts in */
3910 			int addr = DMAADDR(dma_buf, froffs);
3911 			addr = EHCI_PAGE_OFFSET(addr);
3912 			addr += (offs - froffs);
3913 			addr = EHCI_PAGE(addr);
3914 			addr /= EHCI_PAGE_SIZE;
3915 
3916 			/* This gets the initial offset into the first page,
3917 			 * looks how far further along the current uframe
3918 			 * offset is. Works out how many pages that is.
3919 			 */
3920 
3921 			itd->itd.itd_ctl[j] = htole32 ( EHCI_ITD_ACTIVE |
3922 			    EHCI_ITD_SET_LEN(xfer->frlengths[trans_count]) |
3923 			    EHCI_ITD_SET_PG(addr) |
3924 			    EHCI_ITD_SET_OFFS(EHCI_PAGE_OFFSET(DMAADDR(dma_buf,offs))));
3925 
3926 			total_length += xfer->frlengths[trans_count];
3927 			offs += xfer->frlengths[trans_count];
3928 			trans_count++;
3929 
3930 			if (trans_count >= xfer->nframes) { /*Set IOC*/
3931 				itd->itd.itd_ctl[j] |= htole32(EHCI_ITD_IOC);
3932 				break;
3933 			}
3934 		}
3935 
3936 		/* Step 1.75, set buffer pointers. To simplify matters, all
3937 		 * pointers are filled out for the next 7 hardware pages in
3938 		 * the dma block, so no need to worry what pages to cover
3939 		 * and what to not.
3940 		 */
3941 
3942 		for (j=0; j < 7; j++) {
3943 			/*
3944 			 * Don't try to lookup a page that's past the end
3945 			 * of buffer
3946 			 */
3947 			int page_offs = EHCI_PAGE(froffs + (EHCI_PAGE_SIZE * j));
3948 			if (page_offs >= dma_buf->block->size)
3949 				break;
3950 
3951 			long long page = DMAADDR(dma_buf, page_offs);
3952 			page = EHCI_PAGE(page);
3953 			itd->itd.itd_bufr[j] =
3954 			    htole32(EHCI_ITD_SET_BPTR(page));
3955 			itd->itd.itd_bufr_hi[j] =
3956 			    htole32(page >> 32);
3957 		}
3958 
3959 		/*
3960 		 * Other special values
3961 		 */
3962 
3963 		k = epipe->pipe.endpoint->edesc->bEndpointAddress;
3964 		itd->itd.itd_bufr[0] |= htole32(EHCI_ITD_SET_EP(UE_GET_ADDR(k)) |
3965 		    EHCI_ITD_SET_DADDR(epipe->pipe.device->address));
3966 
3967 		k = (UE_GET_DIR(epipe->pipe.endpoint->edesc->bEndpointAddress))
3968 		    ? 1 : 0;
3969 		j = UGETW(epipe->pipe.endpoint->edesc->wMaxPacketSize);
3970 		itd->itd.itd_bufr[1] |= htole32(EHCI_ITD_SET_DIR(k) |
3971 		    EHCI_ITD_SET_MAXPKT(UE_GET_SIZE(j)));
3972 
3973 		/* FIXME: handle invalid trans */
3974 		itd->itd.itd_bufr[2] |=
3975 		    htole32(EHCI_ITD_SET_MULTI(UE_GET_TRANS(j)+1));
3976 
3977 		usb_syncmem(&itd->dma,
3978 		    itd->offs + offsetof(ehci_itd_t, itd_next),
3979                     sizeof(ehci_itd_t),
3980 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3981 
3982 		prev = itd;
3983 	} /* End of frame */
3984 
3985 	stop = itd;
3986 	stop->xfer_next = NULL;
3987 	exfer->isoc_len = total_length;
3988 
3989 	usb_syncmem(&exfer->xfer.dmabuf, 0, total_length,
3990 		BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3991 
3992 	/*
3993 	 * Part 2: Transfer descriptors have now been set up, now they must
3994 	 * be scheduled into the period frame list. Erk. Not wanting to
3995 	 * complicate matters, transfer is denied if the transfer spans
3996 	 * more than the period frame list.
3997 	 */
3998 
3999 	s = splusb();
4000 
4001 	/* Start inserting frames */
4002 	if (epipe->u.isoc.cur_xfers > 0) {
4003 		frindex = epipe->u.isoc.next_frame;
4004 	} else {
4005 		frindex = EOREAD4(sc, EHCI_FRINDEX);
4006 		frindex = frindex >> 3; /* Erase microframe index */
4007 		frindex += 2;
4008 	}
4009 
4010 	if (frindex >= sc->sc_flsize)
4011 		frindex &= (sc->sc_flsize - 1);
4012 
4013 	/* Whats the frame interval? */
4014 	i = (1 << epipe->pipe.endpoint->edesc->bInterval);
4015 	if (i / 8 == 0)
4016 		i = 1;
4017 	else
4018 		i /= 8;
4019 
4020 	itd = start;
4021 	for (j = 0; j < frames; j++) {
4022 		if (itd == NULL)
4023 			panic("ehci: unexpectedly ran out of isoc itds, isoc_start\n");
4024 
4025 		itd->itd.itd_next = sc->sc_flist[frindex];
4026 		if (itd->itd.itd_next == 0)
4027 			/* FIXME: frindex table gets initialized to NULL
4028 			 * or EHCI_NULL? */
4029 			itd->itd.itd_next = htole32(EHCI_NULL);
4030 
4031 		usb_syncmem(&itd->dma,
4032 		    itd->offs + offsetof(ehci_itd_t, itd_next),
4033                     sizeof(itd->itd.itd_next),
4034 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4035 
4036 		sc->sc_flist[frindex] = htole32(EHCI_LINK_ITD | itd->physaddr);
4037 
4038 		usb_syncmem(&sc->sc_fldma,
4039 		    sizeof(ehci_link_t) * frindex,
4040                     sizeof(ehci_link_t),
4041 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4042 
4043 		itd->u.frame_list.next = sc->sc_softitds[frindex];
4044 		sc->sc_softitds[frindex] = itd;
4045 		if (itd->u.frame_list.next != NULL)
4046 			itd->u.frame_list.next->u.frame_list.prev = itd;
4047 		itd->slot = frindex;
4048 		itd->u.frame_list.prev = NULL;
4049 
4050 		frindex += i;
4051 		if (frindex >= sc->sc_flsize)
4052 			frindex -= sc->sc_flsize;
4053 
4054 		itd = itd->xfer_next;
4055 	}
4056 
4057 	epipe->u.isoc.cur_xfers++;
4058 	epipe->u.isoc.next_frame = frindex;
4059 
4060 	exfer->itdstart = start;
4061 	exfer->itdend = stop;
4062 	exfer->sqtdstart = NULL;
4063 	exfer->sqtdstart = NULL;
4064 
4065 	mutex_enter(&sc->sc_intrhead_lock);
4066 	ehci_add_intr_list(sc, exfer);
4067 	mutex_exit(&sc->sc_intrhead_lock);
4068 	xfer->status = USBD_IN_PROGRESS;
4069 	xfer->done = 0;
4070 	splx(s);
4071 
4072 	if (sc->sc_bus.use_polling) {
4073 		printf("Starting ehci isoc xfer with polling. Bad idea?\n");
4074 		ehci_waitintr(sc, xfer);
4075 	}
4076 
4077 	return USBD_IN_PROGRESS;
4078 }
4079 
4080 Static void
4081 ehci_device_isoc_abort(usbd_xfer_handle xfer)
4082 {
4083 	DPRINTFN(1, ("ehci_device_isoc_abort: xfer = %p\n", xfer));
4084 	ehci_abort_isoc_xfer(xfer, USBD_CANCELLED);
4085 }
4086 
4087 Static void
4088 ehci_device_isoc_close(usbd_pipe_handle pipe)
4089 {
4090 	DPRINTFN(1, ("ehci_device_isoc_close: nothing in the pipe to free?\n"));
4091 }
4092 
4093 Static void
4094 ehci_device_isoc_done(usbd_xfer_handle xfer)
4095 {
4096 	struct ehci_xfer *exfer;
4097 	ehci_softc_t *sc;
4098 	struct ehci_pipe *epipe;
4099 	int s;
4100 
4101 	exfer = EXFER(xfer);
4102 	sc = xfer->pipe->device->bus->hci_private;
4103 	epipe = (struct ehci_pipe *) xfer->pipe;
4104 
4105 	s = splusb();
4106 	epipe->u.isoc.cur_xfers--;
4107 	mutex_enter(&sc->sc_intrhead_lock);
4108 	if (xfer->status != USBD_NOMEM && ehci_active_intr_list(exfer)) {
4109 		ehci_del_intr_list(sc, exfer);
4110 		ehci_rem_free_itd_chain(sc, exfer);
4111 	}
4112 	mutex_exit(&sc->sc_intrhead_lock);
4113 	splx(s);
4114 
4115 	usb_syncmem(&xfer->dmabuf, 0, xfer->length, BUS_DMASYNC_POSTWRITE |
4116                     BUS_DMASYNC_POSTREAD);
4117 
4118 }
4119