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