xref: /netbsd-src/sys/dev/usb/ehci.c (revision a45db23f655e22f0c2354600d3b3c2cb98abf2dc)
1 /*	$NetBSD: ehci.c,v 1.317 2023/07/30 12:17:02 skrll Exp $ */
2 
3 /*
4  * Copyright (c) 2004-2012,2016,2020 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (lennart@augustsson.net), Charles M. Hannum,
9  * Jeremy Morse (jeremy.morse@gmail.com), Jared D. McNeill
10  * (jmcneill@invisible.ca). Matthew R. Green (mrg@eterna.com.au), and
11  * Nick Hudson .
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * USB Enhanced Host Controller Driver, a.k.a. USB 2.0 controller.
37  *
38  * The EHCI 1.0 spec can be found at
39  * http://www.intel.com/technology/usb/spec.htm
40  * and the USB 2.0 spec at
41  * http://www.usb.org/developers/docs/
42  *
43  */
44 
45 /*
46  * TODO:
47  * 1) hold off explorations by companion controllers until ehci has started.
48  *
49  * 2) The hub driver needs to handle and schedule the transaction translator,
50  *    to assign place in frame where different devices get to go. See chapter
51  *    on hubs in USB 2.0 for details.
52  *
53  * 3) Command failures are not recovered correctly.
54  */
55 
56 #include <sys/cdefs.h>
57 __KERNEL_RCSID(0, "$NetBSD: ehci.c,v 1.317 2023/07/30 12:17:02 skrll Exp $");
58 
59 #include "ohci.h"
60 #include "uhci.h"
61 
62 #ifdef _KERNEL_OPT
63 #include "opt_usb.h"
64 #endif
65 
66 #include <sys/param.h>
67 
68 #include <sys/bus.h>
69 #include <sys/cpu.h>
70 #include <sys/device.h>
71 #include <sys/kernel.h>
72 #include <sys/kmem.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/queue.h>
76 #include <sys/select.h>
77 #include <sys/sysctl.h>
78 #include <sys/systm.h>
79 #include <sys/reboot.h>
80 
81 #include <machine/endian.h>
82 
83 #include <dev/usb/usb.h>
84 #include <dev/usb/usbdi.h>
85 #include <dev/usb/usbdivar.h>
86 #include <dev/usb/usbhist.h>
87 #include <dev/usb/usb_mem.h>
88 #include <dev/usb/usb_quirks.h>
89 
90 #include <dev/usb/ehcireg.h>
91 #include <dev/usb/ehcivar.h>
92 #include <dev/usb/usbroothub.h>
93 
94 #ifdef USB_DEBUG
95 #ifndef EHCI_DEBUG
96 #define ehcidebug 0
97 #else
98 
99 #ifndef EHCI_DEBUG_DEFAULT
100 #define EHCI_DEBUG_DEFAULT 0
101 #endif
102 
103 static int ehcidebug = EHCI_DEBUG_DEFAULT;
104 
105 SYSCTL_SETUP(sysctl_hw_ehci_setup, "sysctl hw.ehci setup")
106 {
107 	int err;
108 	const struct sysctlnode *rnode;
109 	const struct sysctlnode *cnode;
110 
111 	err = sysctl_createv(clog, 0, NULL, &rnode,
112 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "ehci",
113 	    SYSCTL_DESCR("ehci global controls"),
114 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
115 
116 	if (err)
117 		goto fail;
118 
119 	/* control debugging printfs */
120 	err = sysctl_createv(clog, 0, &rnode, &cnode,
121 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
122 	    "debug", SYSCTL_DESCR("Enable debugging output"),
123 	    NULL, 0, &ehcidebug, sizeof(ehcidebug), CTL_CREATE, CTL_EOL);
124 	if (err)
125 		goto fail;
126 
127 	return;
128 fail:
129 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
130 }
131 
132 #endif /* EHCI_DEBUG */
133 #endif /* USB_DEBUG */
134 
135 #define	DPRINTF(FMT,A,B,C,D)	USBHIST_LOG(ehcidebug,FMT,A,B,C,D)
136 #define	DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(ehcidebug,N,FMT,A,B,C,D)
137 #define	EHCIHIST_FUNC()		USBHIST_FUNC()
138 #define	EHCIHIST_CALLED()	USBHIST_CALLED(ehcidebug)
139 
140 struct ehci_pipe {
141 	struct usbd_pipe pipe;
142 	int nexttoggle;
143 
144 	ehci_soft_qh_t *sqh;
145 	union {
146 		/* Control pipe */
147 		struct {
148 			usb_dma_t reqdma;
149 		} ctrl;
150 		/* Interrupt pipe */
151 		struct {
152 			u_int length;
153 		} intr;
154 		/* Iso pipe */
155 		struct {
156 			u_int next_frame;
157 			u_int cur_xfers;
158 		} isoc;
159 	};
160 };
161 
162 typedef TAILQ_HEAD(ex_completeq, ehci_xfer) ex_completeq_t;
163 
164 Static usbd_status	ehci_open(struct usbd_pipe *);
165 Static void		ehci_poll(struct usbd_bus *);
166 Static void		ehci_softintr(void *);
167 Static int		ehci_intr1(ehci_softc_t *);
168 Static void		ehci_check_qh_intr(ehci_softc_t *, struct ehci_xfer *,
169 			    ex_completeq_t *);
170 Static void		ehci_check_itd_intr(ehci_softc_t *, struct ehci_xfer *,
171 			    ex_completeq_t *);
172 Static void		ehci_check_sitd_intr(ehci_softc_t *, struct ehci_xfer *,
173 			    ex_completeq_t *);
174 Static void		ehci_idone(struct ehci_xfer *, ex_completeq_t *);
175 Static void		ehci_intrlist_timeout(void *);
176 Static void		ehci_doorbell(void *);
177 Static void		ehci_pcd(void *);
178 
179 Static struct usbd_xfer *
180 			ehci_allocx(struct usbd_bus *, unsigned int);
181 Static void		ehci_freex(struct usbd_bus *, struct usbd_xfer *);
182 
183 Static void		ehci_get_lock(struct usbd_bus *, kmutex_t **);
184 Static bool		ehci_dying(struct usbd_bus *);
185 Static int		ehci_roothub_ctrl(struct usbd_bus *,
186 			    usb_device_request_t *, void *, int);
187 
188 Static usbd_status	ehci_root_intr_transfer(struct usbd_xfer *);
189 Static usbd_status	ehci_root_intr_start(struct usbd_xfer *);
190 Static void		ehci_root_intr_abort(struct usbd_xfer *);
191 Static void		ehci_root_intr_close(struct usbd_pipe *);
192 Static void		ehci_root_intr_done(struct usbd_xfer *);
193 
194 Static int		ehci_device_ctrl_init(struct usbd_xfer *);
195 Static void		ehci_device_ctrl_fini(struct usbd_xfer *);
196 Static usbd_status	ehci_device_ctrl_transfer(struct usbd_xfer *);
197 Static usbd_status	ehci_device_ctrl_start(struct usbd_xfer *);
198 Static void		ehci_device_ctrl_abort(struct usbd_xfer *);
199 Static void		ehci_device_ctrl_close(struct usbd_pipe *);
200 Static void		ehci_device_ctrl_done(struct usbd_xfer *);
201 
202 Static int		ehci_device_bulk_init(struct usbd_xfer *);
203 Static void		ehci_device_bulk_fini(struct usbd_xfer *);
204 Static usbd_status	ehci_device_bulk_transfer(struct usbd_xfer *);
205 Static usbd_status	ehci_device_bulk_start(struct usbd_xfer *);
206 Static void		ehci_device_bulk_abort(struct usbd_xfer *);
207 Static void		ehci_device_bulk_close(struct usbd_pipe *);
208 Static void		ehci_device_bulk_done(struct usbd_xfer *);
209 
210 Static int		ehci_device_intr_init(struct usbd_xfer *);
211 Static void		ehci_device_intr_fini(struct usbd_xfer *);
212 Static usbd_status	ehci_device_intr_transfer(struct usbd_xfer *);
213 Static usbd_status	ehci_device_intr_start(struct usbd_xfer *);
214 Static void		ehci_device_intr_abort(struct usbd_xfer *);
215 Static void		ehci_device_intr_close(struct usbd_pipe *);
216 Static void		ehci_device_intr_done(struct usbd_xfer *);
217 
218 Static int		ehci_device_isoc_init(struct usbd_xfer *);
219 Static void		ehci_device_isoc_fini(struct usbd_xfer *);
220 Static usbd_status	ehci_device_isoc_transfer(struct usbd_xfer *);
221 Static void		ehci_device_isoc_abort(struct usbd_xfer *);
222 Static void		ehci_device_isoc_close(struct usbd_pipe *);
223 Static void		ehci_device_isoc_done(struct usbd_xfer *);
224 
225 Static int		ehci_device_fs_isoc_init(struct usbd_xfer *);
226 Static void		ehci_device_fs_isoc_fini(struct usbd_xfer *);
227 Static usbd_status	ehci_device_fs_isoc_transfer(struct usbd_xfer *);
228 Static void		ehci_device_fs_isoc_abort(struct usbd_xfer *);
229 Static void		ehci_device_fs_isoc_close(struct usbd_pipe *);
230 Static void		ehci_device_fs_isoc_done(struct usbd_xfer *);
231 
232 Static void		ehci_device_clear_toggle(struct usbd_pipe *);
233 Static void		ehci_noop(struct usbd_pipe *);
234 
235 Static void		ehci_disown(ehci_softc_t *, int, int);
236 
237 Static ehci_soft_qh_t *	ehci_alloc_sqh(ehci_softc_t *);
238 Static void		ehci_free_sqh(ehci_softc_t *, ehci_soft_qh_t *);
239 
240 Static ehci_soft_qtd_t *ehci_alloc_sqtd(ehci_softc_t *);
241 Static void		ehci_free_sqtd(ehci_softc_t *, ehci_soft_qtd_t *);
242 Static int		ehci_alloc_sqtd_chain(ehci_softc_t *,
243 			    struct usbd_xfer *, int, int, ehci_soft_qtd_t **);
244 Static void		ehci_free_sqtds(ehci_softc_t *, struct ehci_xfer *);
245 
246 Static void		ehci_reset_sqtd_chain(ehci_softc_t *, struct usbd_xfer *,
247 			    int, int, int *, ehci_soft_qtd_t **);
248 Static void		ehci_append_sqtd(ehci_soft_qtd_t *, ehci_soft_qtd_t *);
249 
250 Static ehci_soft_itd_t *ehci_alloc_itd(ehci_softc_t *);
251 Static ehci_soft_sitd_t *
252 			ehci_alloc_sitd(ehci_softc_t *);
253 
254 Static void 		ehci_remove_itd_chain(ehci_softc_t *, ehci_soft_itd_t *);
255 Static void		ehci_remove_sitd_chain(ehci_softc_t *, ehci_soft_sitd_t *);
256 Static void 		ehci_free_itd_chain(ehci_softc_t *, ehci_soft_itd_t *);
257 Static void		ehci_free_sitd_chain(ehci_softc_t *, ehci_soft_sitd_t *);
258 
259 static inline void
260 ehci_free_itd_locked(ehci_softc_t *sc, ehci_soft_itd_t *itd)
261 {
262 
263 	LIST_INSERT_HEAD(&sc->sc_freeitds, itd, free_list);
264 }
265 
266 static inline void
267 ehci_free_sitd_locked(ehci_softc_t *sc, ehci_soft_sitd_t *sitd)
268 {
269 
270 	LIST_INSERT_HEAD(&sc->sc_freesitds, sitd, free_list);
271 }
272 
273 Static void 		ehci_abort_isoc_xfer(struct usbd_xfer *, usbd_status);
274 
275 Static usbd_status	ehci_device_setintr(ehci_softc_t *, ehci_soft_qh_t *,
276 			    int);
277 
278 Static void		ehci_add_qh(ehci_softc_t *, ehci_soft_qh_t *,
279 				    ehci_soft_qh_t *);
280 Static void		ehci_rem_qh(ehci_softc_t *, ehci_soft_qh_t *,
281 				    ehci_soft_qh_t *);
282 Static void		ehci_set_qh_qtd(ehci_soft_qh_t *, ehci_soft_qtd_t *);
283 Static void		ehci_sync_hc(ehci_softc_t *);
284 
285 Static void		ehci_close_pipe(struct usbd_pipe *, ehci_soft_qh_t *);
286 Static void		ehci_abortx(struct usbd_xfer *);
287 
288 #ifdef EHCI_DEBUG
289 Static ehci_softc_t 	*theehci;
290 void			ehci_dump(void);
291 #endif
292 
293 #ifdef EHCI_DEBUG
294 Static void		ehci_dump_regs(ehci_softc_t *);
295 Static void		ehci_dump_sqtds(ehci_soft_qtd_t *);
296 Static void		ehci_dump_sqtd(ehci_soft_qtd_t *);
297 Static void		ehci_dump_qtd(ehci_qtd_t *);
298 Static void		ehci_dump_sqh(ehci_soft_qh_t *);
299 Static void		ehci_dump_sitd(struct ehci_soft_itd *);
300 Static void 		ehci_dump_itds(ehci_soft_itd_t *);
301 Static void		ehci_dump_itd(struct ehci_soft_itd *);
302 Static void		ehci_dump_exfer(struct ehci_xfer *);
303 #endif
304 
305 #define EHCI_NULL htole32(EHCI_LINK_TERMINATE)
306 
307 static inline void
308 ehci_add_intr_list(ehci_softc_t *sc, struct ehci_xfer *ex)
309 {
310 
311 	TAILQ_INSERT_TAIL(&sc->sc_intrhead, ex, ex_next);
312 }
313 
314 static inline void
315 ehci_del_intr_list(ehci_softc_t *sc, struct ehci_xfer *ex)
316 {
317 
318 	TAILQ_REMOVE(&sc->sc_intrhead, ex, ex_next);
319 }
320 
321 Static const struct usbd_bus_methods ehci_bus_methods = {
322 	.ubm_open =	ehci_open,
323 	.ubm_softint =	ehci_softintr,
324 	.ubm_dopoll =	ehci_poll,
325 	.ubm_allocx =	ehci_allocx,
326 	.ubm_freex =	ehci_freex,
327 	.ubm_abortx =	ehci_abortx,
328 	.ubm_dying =	ehci_dying,
329 	.ubm_getlock =	ehci_get_lock,
330 	.ubm_rhctrl =	ehci_roothub_ctrl,
331 };
332 
333 Static const struct usbd_pipe_methods ehci_root_intr_methods = {
334 	.upm_transfer =	ehci_root_intr_transfer,
335 	.upm_start =	ehci_root_intr_start,
336 	.upm_abort =	ehci_root_intr_abort,
337 	.upm_close =	ehci_root_intr_close,
338 	.upm_cleartoggle =	ehci_noop,
339 	.upm_done =	ehci_root_intr_done,
340 };
341 
342 Static const struct usbd_pipe_methods ehci_device_ctrl_methods = {
343 	.upm_init =	ehci_device_ctrl_init,
344 	.upm_fini =	ehci_device_ctrl_fini,
345 	.upm_transfer =	ehci_device_ctrl_transfer,
346 	.upm_start =	ehci_device_ctrl_start,
347 	.upm_abort =	ehci_device_ctrl_abort,
348 	.upm_close =	ehci_device_ctrl_close,
349 	.upm_cleartoggle =	ehci_noop,
350 	.upm_done =	ehci_device_ctrl_done,
351 };
352 
353 Static const struct usbd_pipe_methods ehci_device_intr_methods = {
354 	.upm_init =	ehci_device_intr_init,
355 	.upm_fini =	ehci_device_intr_fini,
356 	.upm_transfer =	ehci_device_intr_transfer,
357 	.upm_start =	ehci_device_intr_start,
358 	.upm_abort =	ehci_device_intr_abort,
359 	.upm_close =	ehci_device_intr_close,
360 	.upm_cleartoggle =	ehci_device_clear_toggle,
361 	.upm_done =	ehci_device_intr_done,
362 };
363 
364 Static const struct usbd_pipe_methods ehci_device_bulk_methods = {
365 	.upm_init =	ehci_device_bulk_init,
366 	.upm_fini =	ehci_device_bulk_fini,
367 	.upm_transfer =	ehci_device_bulk_transfer,
368 	.upm_start =	ehci_device_bulk_start,
369 	.upm_abort =	ehci_device_bulk_abort,
370 	.upm_close =	ehci_device_bulk_close,
371 	.upm_cleartoggle =	ehci_device_clear_toggle,
372 	.upm_done =	ehci_device_bulk_done,
373 };
374 
375 Static const struct usbd_pipe_methods ehci_device_isoc_methods = {
376 	.upm_init =	ehci_device_isoc_init,
377 	.upm_fini =	ehci_device_isoc_fini,
378 	.upm_transfer =	ehci_device_isoc_transfer,
379 	.upm_abort =	ehci_device_isoc_abort,
380 	.upm_close =	ehci_device_isoc_close,
381 	.upm_cleartoggle =	ehci_noop,
382 	.upm_done =	ehci_device_isoc_done,
383 };
384 
385 Static const struct usbd_pipe_methods ehci_device_fs_isoc_methods = {
386 	.upm_init =	ehci_device_fs_isoc_init,
387 	.upm_fini =	ehci_device_fs_isoc_fini,
388 	.upm_transfer =	ehci_device_fs_isoc_transfer,
389 	.upm_abort =	ehci_device_fs_isoc_abort,
390 	.upm_close =	ehci_device_fs_isoc_close,
391 	.upm_cleartoggle = ehci_noop,
392 	.upm_done =	ehci_device_fs_isoc_done,
393 };
394 
395 static const uint8_t revbits[EHCI_MAX_POLLRATE] = {
396 0x00,0x40,0x20,0x60,0x10,0x50,0x30,0x70,0x08,0x48,0x28,0x68,0x18,0x58,0x38,0x78,
397 0x04,0x44,0x24,0x64,0x14,0x54,0x34,0x74,0x0c,0x4c,0x2c,0x6c,0x1c,0x5c,0x3c,0x7c,
398 0x02,0x42,0x22,0x62,0x12,0x52,0x32,0x72,0x0a,0x4a,0x2a,0x6a,0x1a,0x5a,0x3a,0x7a,
399 0x06,0x46,0x26,0x66,0x16,0x56,0x36,0x76,0x0e,0x4e,0x2e,0x6e,0x1e,0x5e,0x3e,0x7e,
400 0x01,0x41,0x21,0x61,0x11,0x51,0x31,0x71,0x09,0x49,0x29,0x69,0x19,0x59,0x39,0x79,
401 0x05,0x45,0x25,0x65,0x15,0x55,0x35,0x75,0x0d,0x4d,0x2d,0x6d,0x1d,0x5d,0x3d,0x7d,
402 0x03,0x43,0x23,0x63,0x13,0x53,0x33,0x73,0x0b,0x4b,0x2b,0x6b,0x1b,0x5b,0x3b,0x7b,
403 0x07,0x47,0x27,0x67,0x17,0x57,0x37,0x77,0x0f,0x4f,0x2f,0x6f,0x1f,0x5f,0x3f,0x7f,
404 };
405 
406 int
407 ehci_init(ehci_softc_t *sc)
408 {
409 	uint32_t vers, hcr;
410 	u_int i;
411 	int err;
412 	ehci_soft_qh_t *sqh;
413 	u_int ncomp;
414 
415 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
416 #ifdef EHCI_DEBUG
417 	theehci = sc;
418 #endif
419 
420 	mutex_init(&sc->sc_rhlock, MUTEX_DEFAULT, IPL_NONE);
421 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
422 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_USB);
423 	cv_init(&sc->sc_doorbell, "ehcidb");
424 
425 	sc->sc_xferpool = pool_cache_init(sizeof(struct ehci_xfer), 0, 0, 0,
426 	    "ehcixfer", NULL, IPL_USB, NULL, NULL, NULL);
427 
428 	sc->sc_doorbell_si = softint_establish(SOFTINT_USB | SOFTINT_MPSAFE,
429 	    ehci_doorbell, sc);
430 	KASSERT(sc->sc_doorbell_si != NULL);
431 	sc->sc_pcd_si = softint_establish(SOFTINT_USB | SOFTINT_MPSAFE,
432 	    ehci_pcd, sc);
433 	KASSERT(sc->sc_pcd_si != NULL);
434 
435 	sc->sc_offs = EREAD1(sc, EHCI_CAPLENGTH);
436 
437 	vers = EREAD2(sc, EHCI_HCIVERSION);
438 	aprint_verbose("%s: EHCI version %x.%x\n", device_xname(sc->sc_dev),
439 	    vers >> 8, vers & 0xff);
440 
441 	const uint32_t hcsparams = EREAD4(sc, EHCI_HCSPARAMS);
442 	DPRINTF("hcsparams=%#jx", hcsparams, 0, 0, 0);
443 	sc->sc_npcomp = EHCI_HCS_N_PCC(hcsparams);
444 	ncomp = EHCI_HCS_N_CC(hcsparams);
445 	if (ncomp != sc->sc_ncomp) {
446 		aprint_verbose("%s: wrong number of companions (%d != %d)\n",
447 		    device_xname(sc->sc_dev), ncomp, sc->sc_ncomp);
448 #if NOHCI == 0 || NUHCI == 0
449 		aprint_error("%s: ohci or uhci probably not configured\n",
450 		    device_xname(sc->sc_dev));
451 #endif
452 		if (ncomp < sc->sc_ncomp)
453 			sc->sc_ncomp = ncomp;
454 	}
455 	if (sc->sc_ncomp > 0) {
456 		KASSERT(!(sc->sc_flags & EHCIF_ETTF));
457 		aprint_normal_dev(sc->sc_dev,
458 		    "%d companion controller%s, %d port%s%s",
459 		    sc->sc_ncomp,
460 		    sc->sc_ncomp!=1 ? "s" : "",
461 		    EHCI_HCS_N_PCC(hcsparams),
462 		    EHCI_HCS_N_PCC(hcsparams)!=1 ? "s" : "",
463 		    sc->sc_ncomp!=1 ? " each" : "");
464 		if (sc->sc_comps[0]) {
465 			aprint_normal(":");
466 			for (i = 0; i < sc->sc_ncomp; i++)
467 				aprint_normal(" %s",
468 				    device_xname(sc->sc_comps[i]));
469 		}
470 		aprint_normal("\n");
471 
472 		mutex_init(&sc->sc_complock, MUTEX_DEFAULT, IPL_USB);
473 		callout_init(&sc->sc_compcallout, CALLOUT_MPSAFE);
474 		cv_init(&sc->sc_compcv, "ehciccv");
475 		sc->sc_comp_state = CO_EARLY;
476 	}
477 	sc->sc_noport = EHCI_HCS_N_PORTS(hcsparams);
478 	sc->sc_hasppc = EHCI_HCS_PPC(hcsparams);
479 
480 	const uint32_t hccparams = EREAD4(sc, EHCI_HCCPARAMS);
481 	DPRINTF("hccparams=%#jx", hccparams, 0, 0, 0);
482 
483 	if (EHCI_HCC_64BIT(hccparams)) {
484 		/* MUST clear segment register if 64 bit capable. */
485 		EOWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);
486 	}
487 
488 	if (hccparams & EHCI_HCC_IST_FULLFRAME) {
489 		sc->sc_istthreshold = 0;
490 	} else {
491 		sc->sc_istthreshold = EHCI_HCC_GET_IST_THRESHOLD(hccparams);
492 	}
493 
494 	sc->sc_bus.ub_revision = USBREV_2_0;
495 	sc->sc_bus.ub_usedma = true;
496 	sc->sc_bus.ub_dmaflags = USBMALLOC_MULTISEG;
497 
498 	/*
499 	 * The bus attachment code will possibly provide a 64bit DMA
500 	 * tag which we now limit to the bottom 4G range as
501 	 *
502 	 * - that's as much as ehci can address in its QH, TD, iTD, and siTD
503 	 *   structures; and
504 	 * - the driver doesn't currently set EHCI_CTRLDSSEGMENT to anything
505 	 *   other than 0.
506 	 */
507 	bus_dma_tag_t ntag = sc->sc_bus.ub_dmatag;
508 	sc->sc_dmatag = sc->sc_bus.ub_dmatag;
509 	err = bus_dmatag_subregion(sc->sc_bus.ub_dmatag, 0, UINT32_MAX,
510 	    &ntag, 0);
511 	if (err == 0) {
512 		sc->sc_dmatag = ntag;
513 		aprint_normal_dev(sc->sc_dev, "Using DMA subregion for control"
514 		    " data structures\n");
515 	}
516 
517 	/* Reset the controller */
518 	DPRINTF("resetting", 0, 0, 0, 0);
519 	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
520 	usb_delay_ms(&sc->sc_bus, 1);
521 	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
522 	for (i = 0; i < 100; i++) {
523 		usb_delay_ms(&sc->sc_bus, 1);
524 		hcr = EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_HCRESET;
525 		if (!hcr)
526 			break;
527 	}
528 	if (hcr) {
529 		aprint_error_dev(sc->sc_dev, "reset timeout\n");
530 		err = EIO;
531 		goto fail1;
532 	}
533 	if (sc->sc_vendor_init)
534 		sc->sc_vendor_init(sc);
535 
536 	/* XXX need proper intr scheduling */
537 	sc->sc_rand = 96;
538 
539 	/* frame list size at default, read back what we got and use that */
540 	switch (EHCI_CMD_FLS(EOREAD4(sc, EHCI_USBCMD))) {
541 	case 0: sc->sc_flsize = 1024; break;
542 	case 1: sc->sc_flsize = 512; break;
543 	case 2: sc->sc_flsize = 256; break;
544 	case 3:
545 		err = EIO;
546 		goto fail1;
547 	}
548 	err = usb_allocmem(sc->sc_dmatag,
549 	    sc->sc_flsize * sizeof(ehci_link_t),
550 	    EHCI_FLALIGN_ALIGN, USBMALLOC_COHERENT, &sc->sc_fldma);
551 	if (err) {
552 		aprint_error_dev(sc->sc_dev, "failed to allocate frame list\n");
553 		goto fail1;
554 	}
555 	DPRINTF("flsize=%jd", sc->sc_flsize, 0, 0, 0);
556 	sc->sc_flist = KERNADDR(&sc->sc_fldma, 0);
557 
558 	for (i = 0; i < sc->sc_flsize; i++) {
559 		sc->sc_flist[i] = EHCI_NULL;
560 	}
561 
562 	const bus_addr_t flba = DMAADDR(&sc->sc_fldma, 0);
563 	const uint32_t hi32 = BUS_ADDR_HI32(flba);
564 	if (hi32 != 0) {
565 		aprint_error_dev(sc->sc_dev, "DMA memory segment error (%08x)\n",
566 		    hi32);
567 		goto fail2;
568 	}
569 
570 	const uint32_t lo32 = BUS_ADDR_LO32(flba);
571 	EOWRITE4(sc, EHCI_PERIODICLISTBASE, lo32);
572 
573 	sc->sc_softitds = kmem_zalloc(sc->sc_flsize * sizeof(ehci_soft_itd_t *),
574 	    KM_SLEEP);
575 	LIST_INIT(&sc->sc_freeitds);
576 	LIST_INIT(&sc->sc_freesitds);
577 	TAILQ_INIT(&sc->sc_intrhead);
578 
579 	/* Set up the bus struct. */
580 	sc->sc_bus.ub_methods = &ehci_bus_methods;
581 	sc->sc_bus.ub_pipesize = sizeof(struct ehci_pipe);
582 
583 	sc->sc_eintrs = EHCI_NORMAL_INTRS;
584 
585 	/*
586 	 * Allocate the interrupt dummy QHs. These are arranged to give poll
587 	 * intervals that are powers of 2 times 1ms.
588 	 */
589 	memset(sc->sc_islots, 0, sizeof(sc->sc_islots));
590 	for (i = 0; i < EHCI_INTRQHS; i++) {
591 		sqh = ehci_alloc_sqh(sc);
592 		if (sqh == NULL) {
593 			err = ENOMEM;
594 			goto fail3;
595 		}
596 		sc->sc_islots[i].sqh = sqh;
597 	}
598 	for (i = 0; i < EHCI_INTRQHS; i++) {
599 		sqh = sc->sc_islots[i].sqh;
600 		if (i == 0) {
601 			/* The last (1ms) QH terminates. */
602 			sqh->qh.qh_link = EHCI_NULL;
603 			sqh->next = NULL;
604 		} else {
605 			/* Otherwise the next QH has half the poll interval */
606 			sqh->next = sc->sc_islots[(i + 1) / 2 - 1].sqh;
607 			sqh->qh.qh_link = htole32(sqh->next->physaddr |
608 			    EHCI_LINK_QH);
609 		}
610 		sqh->qh.qh_endp = htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH));
611 		sqh->qh.qh_endphub = htole32(EHCI_QH_SET_MULT(1));
612 		sqh->qh.qh_curqtd = EHCI_NULL;
613 		sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
614 		sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
615 		sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
616 		sqh->sqtd = NULL;
617 		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
618 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
619 	}
620 	/* Point the frame list at the last level (128ms). */
621 	for (i = 0; i < sc->sc_flsize; i++) {
622 		int j;
623 
624 		j = (i & ~(EHCI_MAX_POLLRATE-1)) |
625 		    revbits[i & (EHCI_MAX_POLLRATE-1)];
626 		sc->sc_flist[j] = htole32(EHCI_LINK_QH |
627 		    sc->sc_islots[EHCI_IQHIDX(EHCI_IPOLLRATES - 1,
628 		    i)].sqh->physaddr);
629 	}
630 	usb_syncmem(&sc->sc_fldma, 0, sc->sc_flsize * sizeof(ehci_link_t),
631 	    BUS_DMASYNC_PREWRITE);
632 
633 	/* Allocate dummy QH that starts the async list. */
634 	sqh = ehci_alloc_sqh(sc);
635 	if (sqh == NULL) {
636 		err = ENOMEM;
637 		goto fail3;
638 	}
639 	/* Fill the QH */
640 	sqh->qh.qh_endp =
641 	    htole32(EHCI_QH_SET_EPS(EHCI_QH_SPEED_HIGH) | EHCI_QH_HRECL);
642 	sqh->qh.qh_link =
643 	    htole32(sqh->physaddr | EHCI_LINK_QH);
644 	sqh->qh.qh_curqtd = EHCI_NULL;
645 	sqh->next = NULL;
646 	/* Fill the overlay qTD */
647 	sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
648 	sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
649 	sqh->qh.qh_qtd.qtd_status = htole32(EHCI_QTD_HALTED);
650 	sqh->sqtd = NULL;
651 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
652 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
653 #ifdef EHCI_DEBUG
654 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
655 	ehci_dump_sqh(sqh);
656 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
657 #endif
658 
659 	/* Point to async list */
660 	sc->sc_async_head = sqh;
661 	EOWRITE4(sc, EHCI_ASYNCLISTADDR, sqh->physaddr | EHCI_LINK_QH);
662 
663 	callout_init(&sc->sc_tmo_intrlist, CALLOUT_MPSAFE);
664 
665 	/* Turn on controller */
666 	EOWRITE4(sc, EHCI_USBCMD,
667 		 EHCI_CMD_ITC_2 | /* 2 microframes interrupt delay */
668 		 (EOREAD4(sc, EHCI_USBCMD) & EHCI_CMD_FLS_M) |
669 		 EHCI_CMD_ASE |
670 		 EHCI_CMD_PSE |
671 		 EHCI_CMD_RS);
672 
673 	/* Take over port ownership */
674 	EOWRITE4(sc, EHCI_CONFIGFLAG, EHCI_CONF_CF);
675 
676 	for (i = 0; i < 100; i++) {
677 		usb_delay_ms(&sc->sc_bus, 1);
678 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
679 		if (!hcr)
680 			break;
681 	}
682 	if (hcr) {
683 		aprint_error("%s: run timeout\n", device_xname(sc->sc_dev));
684 		err = EIO;
685 		goto fail4;
686 	}
687 
688 	/* Enable interrupts */
689 	DPRINTF("enabling interrupts", 0, 0, 0, 0);
690 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
691 
692 	return 0;
693 
694 fail4:
695 	ehci_free_sqh(sc, sc->sc_async_head);
696 
697 fail3:
698 	for (i = 0; i < EHCI_INTRQHS; i++) {
699 		sqh = sc->sc_islots[i].sqh;
700 		if (sqh)
701 			ehci_free_sqh(sc, sqh);
702 	}
703 
704 	kmem_free(sc->sc_softitds, sc->sc_flsize * sizeof(ehci_soft_itd_t *));
705 
706 fail2:
707 	usb_freemem(&sc->sc_fldma);
708 
709 fail1:
710 	softint_disestablish(sc->sc_doorbell_si);
711 	softint_disestablish(sc->sc_pcd_si);
712 	mutex_destroy(&sc->sc_rhlock);
713 	mutex_destroy(&sc->sc_lock);
714 	mutex_destroy(&sc->sc_intr_lock);
715 
716 	return err;
717 }
718 
719 int
720 ehci_intr(void *v)
721 {
722 	ehci_softc_t *sc = v;
723 	int ret = 0;
724 
725 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
726 
727 	if (sc == NULL)
728 		return 0;
729 
730 	mutex_spin_enter(&sc->sc_intr_lock);
731 
732 	if (sc->sc_dying || !device_has_power(sc->sc_dev))
733 		goto done;
734 
735 	/* If we get an interrupt while polling, then just ignore it. */
736 	if (sc->sc_bus.ub_usepolling) {
737 		uint32_t intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
738 
739 		if (intrs)
740 			EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
741 		DPRINTFN(16, "ignored interrupt while polling", 0, 0, 0, 0);
742 		goto done;
743 	}
744 
745 	ret = ehci_intr1(sc);
746 
747 done:
748 	mutex_spin_exit(&sc->sc_intr_lock);
749 	return ret;
750 }
751 
752 Static int
753 ehci_intr1(ehci_softc_t *sc)
754 {
755 	uint32_t intrs, eintrs;
756 
757 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
758 
759 	/* In case the interrupt occurs before initialization has completed. */
760 	if (sc == NULL) {
761 #ifdef DIAGNOSTIC
762 		printf("ehci_intr1: sc == NULL\n");
763 #endif
764 		return 0;
765 	}
766 
767 	KASSERT(mutex_owned(&sc->sc_intr_lock));
768 
769 	intrs = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
770 	if (!intrs)
771 		return 0;
772 
773 	eintrs = intrs & sc->sc_eintrs;
774 	DPRINTF("sc=%#jx intrs=%#jx(%#jx) eintrs=%#jx", (uintptr_t)sc, intrs,
775 	    EOREAD4(sc, EHCI_USBSTS), eintrs);
776 	if (!eintrs)
777 		return 0;
778 
779 	EOWRITE4(sc, EHCI_USBSTS, intrs); /* Acknowledge */
780 	if (eintrs & EHCI_STS_IAA) {
781 		DPRINTF("door bell", 0, 0, 0, 0);
782 		kpreempt_disable();
783 		KASSERT(sc->sc_doorbell_si != NULL);
784 		softint_schedule(sc->sc_doorbell_si);
785 		kpreempt_enable();
786 		eintrs &= ~EHCI_STS_IAA;
787 	}
788 	if (eintrs & (EHCI_STS_INT | EHCI_STS_ERRINT)) {
789 		DPRINTF("INT=%jd  ERRINT=%jd",
790 		    eintrs & EHCI_STS_INT ? 1 : 0,
791 		    eintrs & EHCI_STS_ERRINT ? 1 : 0, 0, 0);
792 		usb_schedsoftintr(&sc->sc_bus);
793 		eintrs &= ~(EHCI_STS_INT | EHCI_STS_ERRINT);
794 	}
795 	if (eintrs & EHCI_STS_HSE) {
796 		printf("%s: unrecoverable error, controller halted\n",
797 		       device_xname(sc->sc_dev));
798 		/* XXX what else */
799 	}
800 	if (eintrs & EHCI_STS_PCD) {
801 		kpreempt_disable();
802 		KASSERT(sc->sc_pcd_si != NULL);
803 		softint_schedule(sc->sc_pcd_si);
804 		kpreempt_enable();
805 		eintrs &= ~EHCI_STS_PCD;
806 	}
807 
808 	if (eintrs != 0) {
809 		/* Block unprocessed interrupts. */
810 		sc->sc_eintrs &= ~eintrs;
811 		EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
812 		printf("%s: blocking intrs %#x\n",
813 		       device_xname(sc->sc_dev), eintrs);
814 	}
815 
816 	return 1;
817 }
818 
819 Static void
820 ehci_doorbell(void *addr)
821 {
822 	ehci_softc_t *sc = addr;
823 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
824 
825 	mutex_enter(&sc->sc_lock);
826 	if (sc->sc_doorbelllwp == NULL)
827 		DPRINTF("spurious doorbell interrupt", 0, 0, 0, 0);
828 	sc->sc_doorbelllwp = NULL;
829 	cv_signal(&sc->sc_doorbell);
830 	mutex_exit(&sc->sc_lock);
831 }
832 
833 Static void
834 ehci_pcd(void *addr)
835 {
836 	ehci_softc_t *sc = addr;
837 	struct usbd_xfer *xfer;
838 	u_char *p;
839 	int i, m;
840 
841 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
842 
843 	mutex_enter(&sc->sc_lock);
844 	xfer = sc->sc_intrxfer;
845 
846 	if (xfer == NULL) {
847 		/* Just ignore the change. */
848 		goto done;
849 	}
850 	KASSERT(xfer->ux_status == USBD_IN_PROGRESS);
851 
852 	p = xfer->ux_buf;
853 	m = uimin(sc->sc_noport, xfer->ux_length * 8 - 1);
854 	memset(p, 0, xfer->ux_length);
855 	for (i = 1; i <= m; i++) {
856 		/* Pick out CHANGE bits from the status reg. */
857 		if (EOREAD4(sc, EHCI_PORTSC(i)) & EHCI_PS_CLEAR)
858 			p[i/8] |= 1 << (i%8);
859 		if (i % 8 == 7)
860 			DPRINTF("change(%jd)=0x%02jx", i / 8, p[i/8], 0, 0);
861 	}
862 	xfer->ux_actlen = xfer->ux_length;
863 	xfer->ux_status = USBD_NORMAL_COMPLETION;
864 
865 	usb_transfer_complete(xfer);
866 
867 done:
868 	mutex_exit(&sc->sc_lock);
869 }
870 
871 Static void
872 ehci_softintr(void *v)
873 {
874 	struct usbd_bus *bus = v;
875 	ehci_softc_t *sc = EHCI_BUS2SC(bus);
876 	struct ehci_xfer *ex, *nextex;
877 
878 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
879 
880 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
881 
882 	ex_completeq_t cq;
883 	TAILQ_INIT(&cq);
884 
885 	/*
886 	 * The only explanation I can think of for why EHCI is as brain dead
887 	 * as UHCI interrupt-wise is that Intel was involved in both.
888 	 * An interrupt just tells us that something is done, we have no
889 	 * clue what, so we need to scan through all active transfers. :-(
890 	 */
891 
892 	/*
893 	 * ehci_idone will remove transfer from sc->sc_intrhead if it's
894 	 * complete and add to our cq list
895 	 *
896 	 */
897 	TAILQ_FOREACH_SAFE(ex, &sc->sc_intrhead, ex_next, nextex) {
898 		switch (ex->ex_type) {
899 		case EX_CTRL:
900 		case EX_BULK:
901 		case EX_INTR:
902 			ehci_check_qh_intr(sc, ex, &cq);
903 			break;
904 		case EX_ISOC:
905 			ehci_check_itd_intr(sc, ex, &cq);
906 			break;
907 		case EX_FS_ISOC:
908 			ehci_check_sitd_intr(sc, ex, &cq);
909 			break;
910 		default:
911 			KASSERT(false);
912 		}
913 
914 	}
915 
916 	/*
917 	 * We abuse ex_next for the interrupt and complete lists and
918 	 * interrupt transfers will get re-added here so use
919 	 * the _SAFE version of TAILQ_FOREACH.
920 	 */
921 	TAILQ_FOREACH_SAFE(ex, &cq, ex_next, nextex) {
922 		usb_transfer_complete(&ex->ex_xfer);
923 	}
924 
925 	/* Schedule a callout to catch any dropped transactions. */
926 	if ((sc->sc_flags & EHCIF_DROPPED_INTR_WORKAROUND) &&
927 	    !TAILQ_EMPTY(&sc->sc_intrhead))
928 		callout_reset(&sc->sc_tmo_intrlist,
929 		    hz, ehci_intrlist_timeout, sc);
930 }
931 
932 Static void
933 ehci_check_qh_intr(ehci_softc_t *sc, struct ehci_xfer *ex, ex_completeq_t *cq)
934 {
935 	ehci_soft_qtd_t *sqtd, *fsqtd, *lsqtd;
936 	uint32_t status;
937 
938 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
939 
940 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
941 
942 	if (ex->ex_type == EX_CTRL) {
943 		fsqtd = ex->ex_setup;
944 		lsqtd = ex->ex_status;
945 	} else {
946 		fsqtd = ex->ex_sqtdstart;
947 		lsqtd = ex->ex_sqtdend;
948 	}
949 	KASSERTMSG(fsqtd != NULL && lsqtd != NULL,
950 	    "xfer %p xt %d fsqtd %p lsqtd %p", ex, ex->ex_type, fsqtd, lsqtd);
951 
952 	/*
953 	 * If the last TD is still active we need to check whether there
954 	 * is an error somewhere in the middle, or whether there was a
955 	 * short packet (SPD and not ACTIVE).
956 	 */
957 	usb_syncmem(&lsqtd->dma,
958 	    lsqtd->offs + offsetof(ehci_qtd_t, qtd_status),
959 	    sizeof(lsqtd->qtd.qtd_status),
960 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
961 	status = le32toh(lsqtd->qtd.qtd_status);
962 	usb_syncmem(&lsqtd->dma,
963 	    lsqtd->offs + offsetof(ehci_qtd_t, qtd_status),
964 	    sizeof(lsqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
965 	if (status & EHCI_QTD_ACTIVE) {
966 		DPRINTFN(10, "active ex=%#jx", (uintptr_t)ex, 0, 0, 0);
967 
968 		/* last qTD has already been checked */
969 		for (sqtd = fsqtd; sqtd != lsqtd; sqtd = sqtd->nextqtd) {
970 			usb_syncmem(&sqtd->dma,
971 			    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
972 			    sizeof(sqtd->qtd.qtd_status),
973 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
974 			status = le32toh(sqtd->qtd.qtd_status);
975 			usb_syncmem(&sqtd->dma,
976 			    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
977 			    sizeof(sqtd->qtd.qtd_status), BUS_DMASYNC_PREREAD);
978 			/* If there's an active QTD the xfer isn't done. */
979 			if (status & EHCI_QTD_ACTIVE)
980 				break;
981 			/* Any kind of error makes the xfer done. */
982 			if (status & EHCI_QTD_HALTED)
983 				goto done;
984 			/* Handle short packets */
985 			if (EHCI_QTD_GET_BYTES(status) != 0) {
986 				/*
987 				 * If we get here for a control transfer then
988 				 * we need to let the hardware complete the
989 				 * status phase.  That is, we're not done
990 				 * quite yet.
991 				 *
992 				 * Otherwise, we're done.
993 				 */
994 				if (ex->ex_type == EX_CTRL) {
995 					break;
996 				}
997 				goto done;
998 			}
999 		}
1000 		DPRINTFN(10, "ex=%#jx std=%#jx still active",
1001 		    (uintptr_t)ex, (uintptr_t)ex->ex_sqtdstart, 0, 0);
1002 #ifdef EHCI_DEBUG
1003 		DPRINTFN(5, "--- still active start ---", 0, 0, 0, 0);
1004 		ehci_dump_sqtds(ex->ex_sqtdstart);
1005 		DPRINTFN(5, "--- still active end ---", 0, 0, 0, 0);
1006 #endif
1007 		return;
1008 	}
1009  done:
1010 	DPRINTFN(10, "ex=%#jx done", (uintptr_t)ex, 0, 0, 0);
1011 	ehci_idone(ex, cq);
1012 }
1013 
1014 Static void
1015 ehci_check_itd_intr(ehci_softc_t *sc, struct ehci_xfer *ex, ex_completeq_t *cq)
1016 {
1017 	ehci_soft_itd_t *itd;
1018 	int i;
1019 
1020 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1021 
1022 	KASSERT(mutex_owned(&sc->sc_lock));
1023 
1024 	if (&ex->ex_xfer != SIMPLEQ_FIRST(&ex->ex_xfer.ux_pipe->up_queue))
1025 		return;
1026 
1027 	KASSERTMSG(ex->ex_itdstart != NULL && ex->ex_itdend != NULL,
1028 	    "xfer %p fitd %p litd %p", ex, ex->ex_itdstart, ex->ex_itdend);
1029 
1030 	itd = ex->ex_itdend;
1031 
1032 	/*
1033 	 * check no active transfers in last itd, meaning we're finished
1034 	 */
1035 
1036 	usb_syncmem(&itd->dma, itd->offs + offsetof(ehci_itd_t, itd_ctl),
1037 	    sizeof(itd->itd.itd_ctl),
1038 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1039 
1040 	for (i = 0; i < EHCI_ITD_NUFRAMES; i++) {
1041 		if (le32toh(itd->itd.itd_ctl[i]) & EHCI_ITD_ACTIVE)
1042 			break;
1043 	}
1044 
1045 	if (i == EHCI_ITD_NUFRAMES) {
1046 		goto done; /* All 8 descriptors inactive, it's done */
1047 	}
1048 
1049 	usb_syncmem(&itd->dma, itd->offs + offsetof(ehci_itd_t, itd_ctl),
1050 	    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_PREREAD);
1051 
1052 	DPRINTFN(10, "ex %#jx itd %#jx still active",
1053 	    (uintptr_t)ex, (uintptr_t)ex->ex_itdstart, 0, 0);
1054 	return;
1055 done:
1056 	DPRINTF("ex %#jx done", (uintptr_t)ex, 0, 0, 0);
1057 	ehci_idone(ex, cq);
1058 }
1059 
1060 void
1061 ehci_check_sitd_intr(ehci_softc_t *sc, struct ehci_xfer *ex, ex_completeq_t *cq)
1062 {
1063 	ehci_soft_sitd_t *sitd;
1064 
1065 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1066 
1067 	KASSERT(mutex_owned(&sc->sc_lock));
1068 
1069 	if (&ex->ex_xfer != SIMPLEQ_FIRST(&ex->ex_xfer.ux_pipe->up_queue))
1070 		return;
1071 
1072 	KASSERTMSG(ex->ex_sitdstart != NULL && ex->ex_sitdend != NULL,
1073 	    "xfer %p fsitd %p lsitd %p", ex, ex->ex_sitdstart, ex->ex_sitdend);
1074 
1075 	sitd = ex->ex_sitdend;
1076 
1077 	/*
1078 	 * check no active transfers in last sitd, meaning we're finished
1079 	 */
1080 
1081 	usb_syncmem(&sitd->dma, sitd->offs + offsetof(ehci_sitd_t, sitd_trans),
1082 	    sizeof(sitd->sitd.sitd_trans),
1083 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1084 
1085 	bool active = ((le32toh(sitd->sitd.sitd_trans) & EHCI_SITD_ACTIVE) != 0);
1086 
1087 	usb_syncmem(&sitd->dma, sitd->offs + offsetof(ehci_sitd_t, sitd_trans),
1088 	    sizeof(sitd->sitd.sitd_trans), BUS_DMASYNC_PREREAD);
1089 
1090 	if (active)
1091 		return;
1092 
1093 	DPRINTFN(10, "ex=%#jx done", (uintptr_t)ex, 0, 0, 0);
1094 	ehci_idone(ex, cq);
1095 }
1096 
1097 Static void
1098 ehci_idone(struct ehci_xfer *ex, ex_completeq_t *cq)
1099 {
1100 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1101 	struct usbd_xfer *xfer = &ex->ex_xfer;
1102 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
1103 	struct ehci_softc *sc = EHCI_XFER2SC(xfer);
1104 	ehci_soft_qtd_t *sqtd, *fsqtd, *lsqtd;
1105 	uint32_t status = 0, nstatus = 0;
1106 	int actlen = 0;
1107 
1108 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
1109 
1110 	DPRINTF("ex=%#jx", (uintptr_t)ex, 0, 0, 0);
1111 
1112 	/*
1113 	 * Try to claim this xfer for completion.  If it has already
1114 	 * completed or aborted, drop it on the floor.
1115 	 */
1116 	if (!usbd_xfer_trycomplete(xfer))
1117 		return;
1118 
1119 #ifdef DIAGNOSTIC
1120 #ifdef EHCI_DEBUG
1121 	if (ex->ex_isdone) {
1122 		DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
1123 		ehci_dump_exfer(ex);
1124 		DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
1125 	}
1126 #endif
1127 	KASSERTMSG(!ex->ex_isdone, "xfer %p type %d status %d", xfer,
1128 	    ex->ex_type, xfer->ux_status);
1129 	ex->ex_isdone = true;
1130 #endif
1131 
1132 	DPRINTF("xfer=%#jx, pipe=%#jx ready", (uintptr_t)xfer,
1133 	    (uintptr_t)epipe, 0, 0);
1134 
1135 	/* The transfer is done, compute actual length and status. */
1136 	if (ex->ex_type == EX_ISOC) {
1137 		/* HS isoc transfer */
1138 
1139 		struct ehci_soft_itd *itd;
1140 		int i, nframes, len, uframes;
1141 
1142 		nframes = 0;
1143 
1144 #ifdef EHCI_DEBUG
1145 		DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
1146 		ehci_dump_itds(ex->ex_itdstart);
1147 		DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
1148 #endif
1149 
1150 		i = xfer->ux_pipe->up_endpoint->ue_edesc->bInterval;
1151 		uframes = uimin(1 << (i - 1), USB_UFRAMES_PER_FRAME);
1152 
1153 		for (itd = ex->ex_itdstart; itd != NULL; itd = itd->xfer_next) {
1154 			usb_syncmem(&itd->dma,
1155 			    itd->offs + offsetof(ehci_itd_t,itd_ctl),
1156 			    sizeof(itd->itd.itd_ctl),
1157 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1158 
1159 			for (i = 0; i < EHCI_ITD_NUFRAMES; i += uframes) {
1160 				/*
1161 				 * XXX - driver didn't fill in the frame full
1162 				 *   of uframes. This leads to scheduling
1163 				 *   inefficiencies, but working around
1164 				 *   this doubles complexity of tracking
1165 				 *   an xfer.
1166 				 */
1167 				if (nframes >= xfer->ux_nframes)
1168 					break;
1169 
1170 				status = le32toh(itd->itd.itd_ctl[i]);
1171 				len = EHCI_ITD_GET_LEN(status);
1172 				if (EHCI_ITD_GET_STATUS(status) != 0)
1173 					len = 0; /*No valid data on error*/
1174 
1175 				xfer->ux_frlengths[nframes++] = len;
1176 				actlen += len;
1177 			}
1178 			usb_syncmem(&itd->dma,
1179 			    itd->offs + offsetof(ehci_itd_t,itd_ctl),
1180 			    sizeof(itd->itd.itd_ctl), BUS_DMASYNC_PREREAD);
1181 
1182 			if (nframes >= xfer->ux_nframes)
1183 				break;
1184 		}
1185 
1186 		xfer->ux_actlen = actlen;
1187 		xfer->ux_status = USBD_NORMAL_COMPLETION;
1188 		goto end;
1189 	} else if (ex->ex_type == EX_FS_ISOC) {
1190 		/* FS isoc transfer */
1191 		struct ehci_soft_sitd *sitd;
1192 		int nframes, len;
1193 
1194 		nframes = 0;
1195 
1196 		for (sitd = ex->ex_sitdstart; sitd != NULL;
1197 		     sitd = sitd->xfer_next) {
1198 			usb_syncmem(&sitd->dma,
1199 			    sitd->offs + offsetof(ehci_sitd_t, sitd_trans),
1200 			    sizeof(sitd->sitd.sitd_trans),
1201 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1202 
1203 			/*
1204 			 * XXX - driver didn't fill in the frame full
1205 			 *   of uframes. This leads to scheduling
1206 			 *   inefficiencies, but working around
1207 			 *   this doubles complexity of tracking
1208 			 *   an xfer.
1209 			 */
1210 			if (nframes >= xfer->ux_nframes)
1211 				break;
1212 
1213 			status = le32toh(sitd->sitd.sitd_trans);
1214 			usb_syncmem(&sitd->dma,
1215 			    sitd->offs + offsetof(ehci_sitd_t, sitd_trans),
1216 			    sizeof(sitd->sitd.sitd_trans), BUS_DMASYNC_PREREAD);
1217 
1218 			len = EHCI_SITD_GET_LEN(status);
1219 			if (status & (EHCI_SITD_ERR|EHCI_SITD_BUFERR|
1220 			    EHCI_SITD_BABBLE|EHCI_SITD_XACTERR|EHCI_SITD_MISS)) {
1221 				/* No valid data on error */
1222 				len = xfer->ux_frlengths[nframes];
1223 			}
1224 
1225 			/*
1226 			 * frlengths[i]: # of bytes to send
1227 			 * len: # of bytes host didn't send
1228 			 */
1229 			xfer->ux_frlengths[nframes] -= len;
1230 			/* frlengths[i]: # of bytes host sent */
1231 			actlen += xfer->ux_frlengths[nframes++];
1232 
1233 			if (nframes >= xfer->ux_nframes)
1234 				break;
1235 	    	}
1236 
1237 		xfer->ux_actlen = actlen;
1238 		xfer->ux_status = USBD_NORMAL_COMPLETION;
1239 		goto end;
1240 	}
1241 	KASSERT(ex->ex_type == EX_CTRL || ex->ex_type == EX_INTR ||
1242 	   ex->ex_type == EX_BULK);
1243 
1244 	/* Continue processing xfers using queue heads */
1245 	if (ex->ex_type == EX_CTRL) {
1246 		fsqtd = ex->ex_setup;
1247 		lsqtd = ex->ex_status;
1248 	} else {
1249 		fsqtd = ex->ex_sqtdstart;
1250 		lsqtd = ex->ex_sqtdend;
1251 	}
1252 #ifdef EHCI_DEBUG
1253 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
1254 	ehci_dump_sqtds(fsqtd);
1255 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
1256 #endif
1257 
1258 	for (sqtd = fsqtd; sqtd != lsqtd->nextqtd; sqtd = sqtd->nextqtd) {
1259 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
1260 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1261 		nstatus = le32toh(sqtd->qtd.qtd_status);
1262 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
1263 		    BUS_DMASYNC_PREREAD);
1264 		if (nstatus & EHCI_QTD_ACTIVE)
1265 			break;
1266 
1267 		status = nstatus;
1268 		if (EHCI_QTD_GET_PID(status) != EHCI_QTD_PID_SETUP)
1269 			actlen += sqtd->len - EHCI_QTD_GET_BYTES(status);
1270 	}
1271 
1272 	/*
1273 	 * If there are left over TDs we need to update the toggle.
1274 	 * The default pipe doesn't need it since control transfers
1275 	 * start the toggle at 0 every time.
1276 	 * For a short transfer we need to update the toggle for the missing
1277 	 * packets within the qTD.
1278 	 */
1279 	if ((sqtd != lsqtd->nextqtd || EHCI_QTD_GET_BYTES(status)) &&
1280 	    xfer->ux_pipe->up_dev->ud_pipe0 != xfer->ux_pipe) {
1281 		DPRINTF("toggle update status=0x%08jx nstatus=0x%08jx",
1282 		    status, nstatus, 0, 0);
1283 #if 0
1284 		ehci_dump_sqh(epipe->sqh);
1285 		ehci_dump_sqtds(ex->ex_sqtdstart);
1286 #endif
1287 		epipe->nexttoggle = EHCI_QTD_GET_TOGGLE(nstatus);
1288 	}
1289 
1290 	DPRINTF("len=%jd actlen=%jd status=0x%08jx", xfer->ux_length, actlen,
1291 	    status, 0);
1292 	xfer->ux_actlen = actlen;
1293 	if (status & EHCI_QTD_HALTED) {
1294 #ifdef EHCI_DEBUG
1295 		DPRINTF("halted addr=%jd endpt=0x%02jx",
1296 		    xfer->ux_pipe->up_dev->ud_addr,
1297 		    xfer->ux_pipe->up_endpoint->ue_edesc->bEndpointAddress,
1298 		    0, 0);
1299 		DPRINTF("cerr=%jd pid=%jd",
1300 		    EHCI_QTD_GET_CERR(status), EHCI_QTD_GET_PID(status),
1301 		    0, 0);
1302 		DPRINTF("active =%jd halted=%jd buferr=%jd babble=%jd",
1303 		    status & EHCI_QTD_ACTIVE ? 1 : 0,
1304 		    status & EHCI_QTD_HALTED ? 1 : 0,
1305 		    status & EHCI_QTD_BUFERR ? 1 : 0,
1306 		    status & EHCI_QTD_BABBLE ? 1 : 0);
1307 
1308 		DPRINTF("xacterr=%jd missed=%jd split =%jd ping  =%jd",
1309 		    status & EHCI_QTD_XACTERR ? 1 : 0,
1310 		    status & EHCI_QTD_MISSEDMICRO ? 1 : 0,
1311 		    status & EHCI_QTD_SPLITXSTATE ? 1 : 0,
1312 		    status & EHCI_QTD_PINGSTATE ? 1 : 0);
1313 
1314 		DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
1315 		ehci_dump_sqh(epipe->sqh);
1316 		ehci_dump_sqtds(ex->ex_sqtdstart);
1317 		DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
1318 #endif
1319 		/* low&full speed has an extra error flag */
1320 		if (EHCI_QH_GET_EPS(epipe->sqh->qh.qh_endp) !=
1321 		    EHCI_QH_SPEED_HIGH)
1322 			status &= EHCI_QTD_STATERRS | EHCI_QTD_PINGSTATE;
1323 		else
1324 			status &= EHCI_QTD_STATERRS;
1325 		if (status == 0) /* no other errors means a stall */ {
1326 			xfer->ux_status = USBD_STALLED;
1327 		} else {
1328 			xfer->ux_status = USBD_IOERROR; /* more info XXX */
1329 		}
1330 		/* XXX need to reset TT on missed microframe */
1331 		if (status & EHCI_QTD_MISSEDMICRO) {
1332 			printf("%s: missed microframe, TT reset not "
1333 			    "implemented, hub might be inoperational\n",
1334 			    device_xname(sc->sc_dev));
1335 		}
1336 	} else {
1337 		xfer->ux_status = USBD_NORMAL_COMPLETION;
1338 	}
1339 
1340     end:
1341 
1342 	ehci_del_intr_list(sc, ex);
1343 	TAILQ_INSERT_TAIL(cq, ex, ex_next);
1344 
1345 	DPRINTF("ex=%#jx done", (uintptr_t)ex, 0, 0, 0);
1346 }
1347 
1348 Static void
1349 ehci_poll(struct usbd_bus *bus)
1350 {
1351 	ehci_softc_t *sc = EHCI_BUS2SC(bus);
1352 
1353 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1354 
1355 #ifdef EHCI_DEBUG
1356 	static int last;
1357 	int new;
1358 	new = EHCI_STS_INTRS(EOREAD4(sc, EHCI_USBSTS));
1359 	if (new != last) {
1360 		DPRINTF("intrs=0x%04jx", new, 0, 0, 0);
1361 		last = new;
1362 	}
1363 #endif
1364 
1365 	if (EOREAD4(sc, EHCI_USBSTS) & sc->sc_eintrs) {
1366 		mutex_spin_enter(&sc->sc_intr_lock);
1367 		ehci_intr1(sc);
1368 		mutex_spin_exit(&sc->sc_intr_lock);
1369 	}
1370 }
1371 
1372 void
1373 ehci_childdet(device_t self, device_t child)
1374 {
1375 	struct ehci_softc *sc = device_private(self);
1376 
1377 	KASSERT(sc->sc_child == child);
1378 	sc->sc_child = NULL;
1379 }
1380 
1381 int
1382 ehci_detach(struct ehci_softc *sc, int flags)
1383 {
1384 	int rv = 0;
1385 
1386 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1387 
1388 	if (sc->sc_child != NULL) {
1389 		rv = config_detach(sc->sc_child, flags);
1390 		if (rv != 0)
1391 			return rv;
1392 	}
1393 
1394 	if (sc->sc_ncomp > 0) {
1395 		mutex_enter(&sc->sc_complock);
1396 		/* XXX try to halt callout instead of waiting */
1397 		while (sc->sc_comp_state == CO_SCHED)
1398 			cv_wait(&sc->sc_compcv, &sc->sc_complock);
1399 		mutex_exit(&sc->sc_complock);
1400 
1401 		callout_halt(&sc->sc_compcallout, NULL);
1402 		callout_destroy(&sc->sc_compcallout);
1403 		cv_destroy(&sc->sc_compcv);
1404 		mutex_destroy(&sc->sc_complock);
1405 	}
1406 
1407 	callout_halt(&sc->sc_tmo_intrlist, NULL);
1408 	callout_destroy(&sc->sc_tmo_intrlist);
1409 
1410 	/* XXX free other data structures */
1411 	if (sc->sc_softitds) {
1412 		kmem_free(sc->sc_softitds,
1413 		    sc->sc_flsize * sizeof(ehci_soft_itd_t *));
1414 	}
1415 	cv_destroy(&sc->sc_doorbell);
1416 
1417 #if 0
1418 	/* XXX destroyed in ehci_pci.c as it controls ehci_intr access */
1419 	softint_disestablish(sc->sc_doorbell_si);
1420 	softint_disestablish(sc->sc_pcd_si);
1421 	mutex_destroy(&sc->sc_rhlock);
1422 	mutex_destroy(&sc->sc_lock);
1423 	mutex_destroy(&sc->sc_intr_lock);
1424 #endif
1425 
1426 	pool_cache_destroy(sc->sc_xferpool);
1427 
1428 	EOWRITE4(sc, EHCI_CONFIGFLAG, 0);
1429 
1430 	return rv;
1431 }
1432 
1433 int
1434 ehci_activate(device_t self, enum devact act)
1435 {
1436 	struct ehci_softc *sc = device_private(self);
1437 
1438 	switch (act) {
1439 	case DVACT_DEACTIVATE:
1440 		sc->sc_dying = 1;
1441 		return 0;
1442 	default:
1443 		return EOPNOTSUPP;
1444 	}
1445 }
1446 
1447 /*
1448  * Handle suspend/resume.
1449  *
1450  * Note that this power handler isn't to be registered directly; the
1451  * bus glue needs to call out to it.
1452  */
1453 bool
1454 ehci_suspend(device_t dv, const pmf_qual_t *qual)
1455 {
1456 	ehci_softc_t *sc = device_private(dv);
1457 	int i;
1458 	uint32_t cmd, hcr;
1459 
1460 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1461 
1462 	mutex_enter(&sc->sc_rhlock);
1463 
1464 	for (i = 1; i <= sc->sc_noport; i++) {
1465 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1466 		if ((cmd & EHCI_PS_PO) == 0 && (cmd & EHCI_PS_PE) == EHCI_PS_PE)
1467 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_SUSP);
1468 	}
1469 
1470 	sc->sc_cmd = EOREAD4(sc, EHCI_USBCMD);
1471 
1472 	cmd = sc->sc_cmd & ~(EHCI_CMD_ASE | EHCI_CMD_PSE);
1473 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1474 
1475 	for (i = 0; i < 100; i++) {
1476 		hcr = EOREAD4(sc, EHCI_USBSTS) & (EHCI_STS_ASS | EHCI_STS_PSS);
1477 		if (hcr == 0)
1478 			break;
1479 
1480 		usb_delay_ms(&sc->sc_bus, 1);
1481 	}
1482 	if (hcr != 0)
1483 		printf("%s: reset timeout\n", device_xname(dv));
1484 
1485 	cmd &= ~EHCI_CMD_RS;
1486 	EOWRITE4(sc, EHCI_USBCMD, cmd);
1487 
1488 	for (i = 0; i < 100; i++) {
1489 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1490 		if (hcr == EHCI_STS_HCH)
1491 			break;
1492 
1493 		usb_delay_ms(&sc->sc_bus, 1);
1494 	}
1495 	if (hcr != EHCI_STS_HCH)
1496 		printf("%s: config timeout\n", device_xname(dv));
1497 
1498 	mutex_exit(&sc->sc_rhlock);
1499 
1500 	return true;
1501 }
1502 
1503 bool
1504 ehci_resume(device_t dv, const pmf_qual_t *qual)
1505 {
1506 	ehci_softc_t *sc = device_private(dv);
1507 	int i;
1508 	uint32_t cmd, hcr;
1509 
1510 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1511 
1512 	mutex_enter(&sc->sc_rhlock);
1513 
1514 	/* restore things in case the bios sucks */
1515 	EOWRITE4(sc, EHCI_CTRLDSSEGMENT, 0);
1516 	EOWRITE4(sc, EHCI_PERIODICLISTBASE, DMAADDR(&sc->sc_fldma, 0));
1517 	EOWRITE4(sc, EHCI_ASYNCLISTADDR,
1518 	    sc->sc_async_head->physaddr | EHCI_LINK_QH);
1519 
1520 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs & ~EHCI_INTR_PCIE);
1521 
1522 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1523 
1524 	hcr = 0;
1525 	for (i = 1; i <= sc->sc_noport; i++) {
1526 		cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1527 		if ((cmd & EHCI_PS_PO) == 0 &&
1528 		    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP) {
1529 			EOWRITE4(sc, EHCI_PORTSC(i), cmd | EHCI_PS_FPR);
1530 			hcr = 1;
1531 		}
1532 	}
1533 
1534 	if (hcr) {
1535 		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
1536 
1537 		for (i = 1; i <= sc->sc_noport; i++) {
1538 			cmd = EOREAD4(sc, EHCI_PORTSC(i)) & ~EHCI_PS_CLEAR;
1539 			if ((cmd & EHCI_PS_PO) == 0 &&
1540 			    (cmd & EHCI_PS_SUSP) == EHCI_PS_SUSP)
1541 				EOWRITE4(sc, EHCI_PORTSC(i),
1542 				    cmd & ~EHCI_PS_FPR);
1543 		}
1544 	}
1545 
1546 	EOWRITE4(sc, EHCI_USBCMD, sc->sc_cmd);
1547 	EOWRITE4(sc, EHCI_USBINTR, sc->sc_eintrs);
1548 
1549 	for (i = 0; i < 100; i++) {
1550 		hcr = EOREAD4(sc, EHCI_USBSTS) & EHCI_STS_HCH;
1551 		if (hcr != EHCI_STS_HCH)
1552 			break;
1553 
1554 		usb_delay_ms(&sc->sc_bus, 1);
1555 	}
1556 	if (hcr == EHCI_STS_HCH)
1557 		printf("%s: config timeout\n", device_xname(dv));
1558 
1559 	mutex_exit(&sc->sc_rhlock);
1560 
1561 	return true;
1562 }
1563 
1564 /*
1565  * Shut down the controller when the system is going down.
1566  */
1567 bool
1568 ehci_shutdown(device_t self, int flags)
1569 {
1570 	ehci_softc_t *sc = device_private(self);
1571 
1572 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1573 
1574 	EOWRITE4(sc, EHCI_USBCMD, 0);	/* Halt controller */
1575 	EOWRITE4(sc, EHCI_USBCMD, EHCI_CMD_HCRESET);
1576 	return true;
1577 }
1578 
1579 Static struct usbd_xfer *
1580 ehci_allocx(struct usbd_bus *bus, unsigned int nframes)
1581 {
1582 	struct ehci_softc *sc = EHCI_BUS2SC(bus);
1583 	struct usbd_xfer *xfer;
1584 
1585 	xfer = pool_cache_get(sc->sc_xferpool, PR_WAITOK);
1586 	if (xfer != NULL) {
1587 		memset(xfer, 0, sizeof(struct ehci_xfer));
1588 
1589 #ifdef DIAGNOSTIC
1590 		struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
1591 		ex->ex_isdone = true;
1592 		xfer->ux_state = XFER_BUSY;
1593 #endif
1594 	}
1595 	return xfer;
1596 }
1597 
1598 Static void
1599 ehci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
1600 {
1601 	struct ehci_softc *sc = EHCI_BUS2SC(bus);
1602 	struct ehci_xfer *ex __diagused = EHCI_XFER2EXFER(xfer);
1603 
1604 	KASSERTMSG(xfer->ux_state == XFER_BUSY ||
1605 	    xfer->ux_status == USBD_NOT_STARTED,
1606 	    "xfer %p state %d\n", xfer, xfer->ux_state);
1607 	KASSERT(ex->ex_isdone || xfer->ux_status == USBD_NOT_STARTED);
1608 
1609 #ifdef DIAGNOSTIC
1610 	xfer->ux_state = XFER_FREE;
1611 #endif
1612 
1613 	pool_cache_put(sc->sc_xferpool, xfer);
1614 }
1615 
1616 Static bool
1617 ehci_dying(struct usbd_bus *bus)
1618 {
1619 	struct ehci_softc *sc = EHCI_BUS2SC(bus);
1620 
1621 	return sc->sc_dying;
1622 }
1623 
1624 Static void
1625 ehci_get_lock(struct usbd_bus *bus, kmutex_t **lock)
1626 {
1627 	struct ehci_softc *sc = EHCI_BUS2SC(bus);
1628 
1629 	*lock = &sc->sc_lock;
1630 }
1631 
1632 Static void
1633 ehci_device_clear_toggle(struct usbd_pipe *pipe)
1634 {
1635 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(pipe);
1636 
1637 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1638 
1639 	DPRINTF("epipe=%#jx status=0x%08jx", (uintptr_t)epipe,
1640 	    epipe->sqh->qh.qh_qtd.qtd_status, 0, 0);
1641 #ifdef EHCI_DEBUG
1642 	if (ehcidebug)
1643 		usbd_dump_pipe(pipe);
1644 #endif
1645 	epipe->nexttoggle = 0;
1646 }
1647 
1648 Static void
1649 ehci_noop(struct usbd_pipe *pipe)
1650 {
1651 }
1652 
1653 #ifdef EHCI_DEBUG
1654 /*
1655  * Unused function - this is meant to be called from a kernel
1656  * debugger.
1657  */
1658 void
1659 ehci_dump(void)
1660 {
1661 	ehci_softc_t *sc = theehci;
1662 	int i;
1663 	printf("cmd=0x%08x, sts=0x%08x, ien=0x%08x\n",
1664 	    EOREAD4(sc, EHCI_USBCMD),
1665 	    EOREAD4(sc, EHCI_USBSTS),
1666 	    EOREAD4(sc, EHCI_USBINTR));
1667 	printf("frindex=0x%08x ctrdsegm=0x%08x periodic=0x%08x async=0x%08x\n",
1668 	    EOREAD4(sc, EHCI_FRINDEX),
1669 	    EOREAD4(sc, EHCI_CTRLDSSEGMENT),
1670 	    EOREAD4(sc, EHCI_PERIODICLISTBASE),
1671 	    EOREAD4(sc, EHCI_ASYNCLISTADDR));
1672 	for (i = 1; i <= sc->sc_noport; i++)
1673 		printf("port %d status=0x%08x\n", i,
1674 		    EOREAD4(sc, EHCI_PORTSC(i)));
1675 }
1676 
1677 Static void
1678 ehci_dump_regs(ehci_softc_t *sc)
1679 {
1680 	int i;
1681 
1682 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1683 
1684 	DPRINTF("cmd     = 0x%08jx  sts      = 0x%08jx  ien      = 0x%08jx",
1685 	    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS),
1686 	    EOREAD4(sc, EHCI_USBINTR), 0);
1687 	DPRINTF("frindex = 0x%08jx  ctrdsegm = 0x%08jx  periodic = 0x%08jx  "
1688 	    "async   = 0x%08jx",
1689 	    EOREAD4(sc, EHCI_FRINDEX), EOREAD4(sc, EHCI_CTRLDSSEGMENT),
1690 	    EOREAD4(sc, EHCI_PERIODICLISTBASE),
1691 	    EOREAD4(sc, EHCI_ASYNCLISTADDR));
1692 	for (i = 1; i <= sc->sc_noport; i += 2) {
1693 		if (i == sc->sc_noport) {
1694 			DPRINTF("port %jd status = 0x%08jx", i,
1695 			    EOREAD4(sc, EHCI_PORTSC(i)), 0, 0);
1696 		} else {
1697 			DPRINTF("port %jd status = 0x%08jx  port %jd "
1698 			    "status = 0x%08jx",
1699 			    i, EOREAD4(sc, EHCI_PORTSC(i)),
1700 			    i+1, EOREAD4(sc, EHCI_PORTSC(i+1)));
1701 		}
1702 	}
1703 }
1704 
1705 #define ehci_dump_link(link, type) do {					\
1706 	DPRINTF("    link 0x%08jx (T = %jd):",				\
1707 	    link,							\
1708 	    link & EHCI_LINK_TERMINATE ? 1 : 0, 0, 0);			\
1709 	if (type) {							\
1710 		DPRINTF(						\
1711 		    "        ITD  = %jd  QH   = %jd  SITD = %jd  FSTN = %jd",\
1712 		    EHCI_LINK_TYPE(link) == EHCI_LINK_ITD ? 1 : 0,	\
1713 		    EHCI_LINK_TYPE(link) == EHCI_LINK_QH ? 1 : 0,	\
1714 		    EHCI_LINK_TYPE(link) == EHCI_LINK_SITD ? 1 : 0,	\
1715 		    EHCI_LINK_TYPE(link) == EHCI_LINK_FSTN ? 1 : 0);	\
1716 	}								\
1717 } while(0)
1718 
1719 Static void
1720 ehci_dump_sqtds(ehci_soft_qtd_t *sqtd)
1721 {
1722 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1723 	int i;
1724 	uint32_t stop = 0;
1725 
1726 	for (i = 0; sqtd && i < 20 && !stop; sqtd = sqtd->nextqtd, i++) {
1727 		ehci_dump_sqtd(sqtd);
1728 		usb_syncmem(&sqtd->dma,
1729 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1730 		    sizeof(sqtd->qtd),
1731 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1732 		stop = sqtd->qtd.qtd_next & htole32(EHCI_LINK_TERMINATE);
1733 		usb_syncmem(&sqtd->dma,
1734 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_next),
1735 		    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1736 	}
1737 	if (!stop)
1738 		DPRINTF("dump aborted, too many TDs", 0, 0, 0, 0);
1739 }
1740 
1741 Static void
1742 ehci_dump_sqtd(ehci_soft_qtd_t *sqtd)
1743 {
1744 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1745 
1746 	usb_syncmem(&sqtd->dma, sqtd->offs,
1747 	    sizeof(sqtd->qtd), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1748 
1749 	DPRINTFN(10, "QTD(%#jx) at 0x%08jx:", (uintptr_t)sqtd, sqtd->physaddr,
1750 	    0, 0);
1751 	ehci_dump_qtd(&sqtd->qtd);
1752 
1753 	usb_syncmem(&sqtd->dma, sqtd->offs,
1754 	    sizeof(sqtd->qtd), BUS_DMASYNC_PREREAD);
1755 }
1756 
1757 Static void
1758 ehci_dump_qtd(ehci_qtd_t *qtd)
1759 {
1760 	EHCIHIST_FUNC();	EHCIHIST_CALLED();
1761 	uint32_t s = le32toh(qtd->qtd_status);
1762 
1763 	DPRINTFN(10,
1764 	    "     next = 0x%08jx  altnext = 0x%08jx  status = 0x%08jx",
1765 	    qtd->qtd_next, qtd->qtd_altnext, s, 0);
1766 	DPRINTFN(10,
1767 	    "   toggle = %jd ioc = %jd bytes = %#jx c_page = %#jx",
1768 	    EHCI_QTD_GET_TOGGLE(s), EHCI_QTD_GET_IOC(s),
1769 	    EHCI_QTD_GET_BYTES(s), EHCI_QTD_GET_C_PAGE(s));
1770 	DPRINTFN(10,
1771 	    "     cerr = %jd pid = %jd stat  = %jx",
1772 	    EHCI_QTD_GET_CERR(s), EHCI_QTD_GET_PID(s), EHCI_QTD_GET_STATUS(s),
1773 	    0);
1774 	DPRINTFN(10,
1775 	    "active =%jd halted=%jd buferr=%jd babble=%jd",
1776 	    s & EHCI_QTD_ACTIVE ? 1 : 0,
1777 	    s & EHCI_QTD_HALTED ? 1 : 0,
1778 	    s & EHCI_QTD_BUFERR ? 1 : 0,
1779 	    s & EHCI_QTD_BABBLE ? 1 : 0);
1780 	DPRINTFN(10,
1781 	    "xacterr=%jd missed=%jd split =%jd ping  =%jd",
1782 	    s & EHCI_QTD_XACTERR ? 1 : 0,
1783 	    s & EHCI_QTD_MISSEDMICRO ? 1 : 0,
1784 	    s & EHCI_QTD_SPLITXSTATE ? 1 : 0,
1785 	    s & EHCI_QTD_PINGSTATE ? 1 : 0);
1786 	DPRINTFN(10,
1787 	    "buffer[0] = %#jx  buffer[1] = %#jx  "
1788 	    "buffer[2] = %#jx  buffer[3] = %#jx",
1789 	    le32toh(qtd->qtd_buffer[0]), le32toh(qtd->qtd_buffer[1]),
1790 	    le32toh(qtd->qtd_buffer[2]), le32toh(qtd->qtd_buffer[3]));
1791 	DPRINTFN(10,
1792 	    "buffer[4] = %#jx", le32toh(qtd->qtd_buffer[4]), 0, 0, 0);
1793 }
1794 
1795 Static void
1796 ehci_dump_sqh(ehci_soft_qh_t *sqh)
1797 {
1798 	ehci_qh_t *qh = &sqh->qh;
1799 	ehci_link_t link;
1800 	uint32_t endp, endphub;
1801 	EHCIHIST_FUNC();	EHCIHIST_CALLED();
1802 
1803 	usb_syncmem(&sqh->dma, sqh->offs,
1804 	    sizeof(sqh->qh), BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1805 
1806 	DPRINTFN(10, "QH(%#jx) at %#jx:", (uintptr_t)sqh, sqh->physaddr, 0, 0);
1807 	link = le32toh(qh->qh_link);
1808 	ehci_dump_link(link, true);
1809 
1810 	endp = le32toh(qh->qh_endp);
1811 	DPRINTFN(10, "    endp = %#jx", endp, 0, 0, 0);
1812 	DPRINTFN(10, "        addr = 0x%02jx  inact = %jd  endpt = %jd  "
1813 	    "eps = %jd",
1814 	    EHCI_QH_GET_ADDR(endp), EHCI_QH_GET_INACT(endp),
1815 	    EHCI_QH_GET_ENDPT(endp), EHCI_QH_GET_EPS(endp));
1816 	DPRINTFN(10, "        dtc  = %jd     hrecl = %jd",
1817 	    EHCI_QH_GET_DTC(endp), EHCI_QH_GET_HRECL(endp), 0, 0);
1818 	DPRINTFN(10, "        ctl  = %jd     nrl   = %jd  mpl   = %#jx(%jd)",
1819 	    EHCI_QH_GET_CTL(endp),EHCI_QH_GET_NRL(endp),
1820 	    EHCI_QH_GET_MPL(endp), EHCI_QH_GET_MPL(endp));
1821 
1822 	endphub = le32toh(qh->qh_endphub);
1823 	DPRINTFN(10, " endphub = %#jx", endphub, 0, 0, 0);
1824 	DPRINTFN(10, "      smask = 0x%02jx  cmask = 0x%02jx one %jx",
1825 	    EHCI_QH_GET_SMASK(endphub), EHCI_QH_GET_CMASK(endphub), 1, 0);
1826 	DPRINTFN(10, "      huba  = 0x%02jx  port  = %jd  mult = %jd",
1827 	    EHCI_QH_GET_HUBA(endphub), EHCI_QH_GET_PORT(endphub),
1828 	    EHCI_QH_GET_MULT(endphub), 0);
1829 
1830 	link = le32toh(qh->qh_curqtd);
1831 	ehci_dump_link(link, false);
1832 	DPRINTFN(10, "Overlay qTD:", 0, 0, 0, 0);
1833 	ehci_dump_qtd(&qh->qh_qtd);
1834 
1835 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
1836 	    BUS_DMASYNC_PREREAD);
1837 }
1838 
1839 Static void
1840 ehci_dump_itds(ehci_soft_itd_t *itd)
1841 {
1842 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1843 	int i;
1844 	uint32_t stop = 0;
1845 
1846 	for (i = 0; itd && i < 20 && !stop; itd = itd->xfer_next, i++) {
1847 		ehci_dump_itd(itd);
1848 		usb_syncmem(&itd->dma,
1849 		    itd->offs + offsetof(ehci_itd_t, itd_next),
1850 		    sizeof(itd->itd),
1851 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
1852 		stop = itd->itd.itd_next & htole32(EHCI_LINK_TERMINATE);
1853 		usb_syncmem(&itd->dma,
1854 		    itd->offs + offsetof(ehci_itd_t, itd_next),
1855 		    sizeof(itd->itd), BUS_DMASYNC_PREREAD);
1856 	}
1857 	if (!stop)
1858 		DPRINTF("dump aborted, too many TDs", 0, 0, 0, 0);
1859 }
1860 
1861 Static void
1862 ehci_dump_itd(struct ehci_soft_itd *itd)
1863 {
1864 	ehci_isoc_trans_t t;
1865 	ehci_isoc_bufr_ptr_t b, b2, b3;
1866 	int i;
1867 
1868 	EHCIHIST_FUNC();	EHCIHIST_CALLED();
1869 
1870 	DPRINTF("ITD: next phys = %#jx", itd->itd.itd_next, 0, 0, 0);
1871 
1872 	for (i = 0; i < EHCI_ITD_NUFRAMES; i++) {
1873 		t = le32toh(itd->itd.itd_ctl[i]);
1874 		DPRINTF("ITDctl %jd: stat = %jx len = %jx",
1875 		    i, EHCI_ITD_GET_STATUS(t), EHCI_ITD_GET_LEN(t), 0);
1876 		DPRINTF("     ioc = %jx pg = %jx offs = %jx",
1877 		    EHCI_ITD_GET_IOC(t), EHCI_ITD_GET_PG(t),
1878 		    EHCI_ITD_GET_OFFS(t), 0);
1879 	}
1880 	DPRINTF("ITDbufr: ", 0, 0, 0, 0);
1881 	for (i = 0; i < EHCI_ITD_NBUFFERS; i++)
1882 		DPRINTF("      %jx",
1883 		    EHCI_ITD_GET_BPTR(le32toh(itd->itd.itd_bufr[i])), 0, 0, 0);
1884 
1885 	b = le32toh(itd->itd.itd_bufr[0]);
1886 	b2 = le32toh(itd->itd.itd_bufr[1]);
1887 	b3 = le32toh(itd->itd.itd_bufr[2]);
1888 	DPRINTF("     ep = %jx daddr = %jx dir = %jd",
1889 	    EHCI_ITD_GET_EP(b), EHCI_ITD_GET_DADDR(b), EHCI_ITD_GET_DIR(b2), 0);
1890 	DPRINTF("     maxpkt = %jx multi = %jx",
1891 	    EHCI_ITD_GET_MAXPKT(b2), EHCI_ITD_GET_MULTI(b3), 0, 0);
1892 }
1893 
1894 Static void
1895 ehci_dump_sitd(struct ehci_soft_itd *itd)
1896 {
1897 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1898 
1899 	DPRINTF("SITD %#jx next = %p prev = %#jx",
1900 	    (uintptr_t)itd, (uintptr_t)itd->frame_list.next,
1901 	    (uintptr_t)itd->frame_list.prev, 0);
1902 	DPRINTF("        xfernext=%#jx physaddr=%jX slot=%jd",
1903 	    (uintptr_t)itd->xfer_next, itd->physaddr, itd->slot, 0);
1904 }
1905 
1906 Static void
1907 ehci_dump_exfer(struct ehci_xfer *ex)
1908 {
1909 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1910 
1911 	DPRINTF("ex = %#jx type %jd isdone %jd", (uintptr_t)ex, ex->ex_type,
1912 	    ex->ex_isdone, 0);
1913 
1914 	switch (ex->ex_type) {
1915 	case EX_CTRL:
1916 		DPRINTF("   setup = %#jx data = %#jx status = %#jx",
1917 		    (uintptr_t)ex->ex_setup, (uintptr_t)ex->ex_data,
1918 		    (uintptr_t)ex->ex_status, 0);
1919 		break;
1920 	case EX_BULK:
1921 	case EX_INTR:
1922 		DPRINTF("   qtdstart = %#jx qtdend = %#jx",
1923 		    (uintptr_t)ex->ex_sqtdstart, (uintptr_t)ex->ex_sqtdend,
1924 		    0, 0);
1925 		break;
1926 	case EX_ISOC:
1927 		DPRINTF("   itdstart = %#jx itdend = %#jx",
1928 		    (uintptr_t)ex->ex_itdstart, (uintptr_t)ex->ex_itdend, 0, 0);
1929 		break;
1930 	case EX_FS_ISOC:
1931 		DPRINTF("   sitdstart = %#jx sitdend = %#jx",
1932 		    (uintptr_t)ex->ex_sitdstart, (uintptr_t)ex->ex_sitdend,
1933 		    0, 0);
1934 		break;
1935 	default:
1936 		DPRINTF("   unknown type", 0, 0, 0, 0);
1937 	}
1938 }
1939 #endif
1940 
1941 Static usbd_status
1942 ehci_open(struct usbd_pipe *pipe)
1943 {
1944 	struct usbd_device *dev = pipe->up_dev;
1945 	ehci_softc_t *sc = EHCI_PIPE2SC(pipe);
1946 	usb_endpoint_descriptor_t *ed = pipe->up_endpoint->ue_edesc;
1947 	uint8_t rhaddr = dev->ud_bus->ub_rhaddr;
1948 	uint8_t addr = dev->ud_addr;
1949 	uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1950 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(pipe);
1951 	ehci_soft_qh_t *sqh;
1952 	usbd_status err;
1953 	int ival, speed, naks;
1954 	int hshubaddr, hshubport;
1955 
1956 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
1957 
1958 	DPRINTF("pipe=%#jx, addr=%jd, endpt=%jd (%jd)", (uintptr_t)pipe, addr,
1959 	    ed->bEndpointAddress, rhaddr);
1960 
1961 	if (dev->ud_myhsport) {
1962 		/*
1963 		 * When directly attached FS/LS device while doing embedded
1964 		 * transaction translations and we are the hub, set the hub
1965 		 * address to 0 (us).
1966 		 */
1967 		if (!(sc->sc_flags & EHCIF_ETTF)
1968 		    || (dev->ud_myhsport->up_parent->ud_addr != rhaddr)) {
1969 			hshubaddr = dev->ud_myhsport->up_parent->ud_addr;
1970 		} else {
1971 			hshubaddr = 0;
1972 		}
1973 		hshubport = dev->ud_myhsport->up_portno;
1974 	} else {
1975 		hshubaddr = 0;
1976 		hshubport = 0;
1977 	}
1978 
1979 	if (sc->sc_dying)
1980 		return USBD_IOERROR;
1981 
1982 	/* toggle state needed for bulk endpoints */
1983 	epipe->nexttoggle = pipe->up_endpoint->ue_toggle;
1984 
1985 	if (addr == rhaddr) {
1986 		switch (ed->bEndpointAddress) {
1987 		case USB_CONTROL_ENDPOINT:
1988 			pipe->up_methods = &roothub_ctrl_methods;
1989 			break;
1990 		case UE_DIR_IN | USBROOTHUB_INTR_ENDPT:
1991 			pipe->up_methods = &ehci_root_intr_methods;
1992 			break;
1993 		default:
1994 			DPRINTF("bad bEndpointAddress 0x%02jx",
1995 			    ed->bEndpointAddress, 0, 0, 0);
1996 			return USBD_INVAL;
1997 		}
1998 		return USBD_NORMAL_COMPLETION;
1999 	}
2000 
2001 	/* XXX All this stuff is only valid for async. */
2002 	switch (dev->ud_speed) {
2003 	case USB_SPEED_LOW:  speed = EHCI_QH_SPEED_LOW;  break;
2004 	case USB_SPEED_FULL: speed = EHCI_QH_SPEED_FULL; break;
2005 	case USB_SPEED_HIGH: speed = EHCI_QH_SPEED_HIGH; break;
2006 	default: panic("ehci_open: bad device speed %d", dev->ud_speed);
2007 	}
2008 	if (speed == EHCI_QH_SPEED_LOW && xfertype == UE_ISOCHRONOUS) {
2009 		DPRINTF("hshubaddr=%jd hshubport=%jd", hshubaddr, hshubport, 0,
2010 		    0);
2011 		return USBD_INVAL;
2012 	}
2013 
2014 	/*
2015 	 * For interrupt transfer, nak throttling must be disabled, but for
2016 	 * the other transfer type, nak throttling should be enabled from the
2017 	 * viewpoint that avoids the memory thrashing.
2018 	 */
2019 	naks = (xfertype == UE_INTERRUPT) ? 0
2020 	    : ((speed == EHCI_QH_SPEED_HIGH) ? 4 : 0);
2021 
2022 	/* Allocate sqh for everything, save isoc xfers */
2023 	if (xfertype != UE_ISOCHRONOUS) {
2024 		sqh = ehci_alloc_sqh(sc);
2025 		if (sqh == NULL)
2026 			return USBD_NOMEM;
2027 		/* qh_link filled when the QH is added */
2028 		sqh->qh.qh_endp = htole32(
2029 		    EHCI_QH_SET_ADDR(addr) |
2030 		    EHCI_QH_SET_ENDPT(UE_GET_ADDR(ed->bEndpointAddress)) |
2031 		    EHCI_QH_SET_EPS(speed) |
2032 		    EHCI_QH_DTC |
2033 		    EHCI_QH_SET_MPL(UGETW(ed->wMaxPacketSize)) |
2034 		    (speed != EHCI_QH_SPEED_HIGH && xfertype == UE_CONTROL ?
2035 		     EHCI_QH_CTL : 0) |
2036 		    EHCI_QH_SET_NRL(naks)
2037 		    );
2038 		sqh->qh.qh_endphub = htole32(
2039 		    EHCI_QH_SET_MULT(1) |
2040 		    (xfertype == UE_INTERRUPT ?
2041 			EHCI_QH_SET_SMASK(__BIT(1))	   /* Start Split Y1 */
2042 			: 0)
2043 		    );
2044 		if (speed != EHCI_QH_SPEED_HIGH)
2045 			sqh->qh.qh_endphub |= htole32(
2046 			    EHCI_QH_SET_PORT(hshubport) |
2047 			    EHCI_QH_SET_HUBA(hshubaddr) |
2048 			    (xfertype == UE_INTERRUPT ?
2049 				 EHCI_QH_SET_CMASK(__BITS(3,5)) /* CS Y[345] */
2050 				 : 0)
2051 			);
2052 		sqh->qh.qh_curqtd = EHCI_NULL;
2053 		/* Fill the overlay qTD */
2054 		sqh->qh.qh_qtd.qtd_next = EHCI_NULL;
2055 		sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
2056 		sqh->qh.qh_qtd.qtd_status = htole32(0);
2057 
2058 		usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
2059 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2060 		epipe->sqh = sqh;
2061 	} else {
2062 		sqh = NULL;
2063 	} /*xfertype == UE_ISOC*/
2064 
2065 	switch (xfertype) {
2066 	case UE_CONTROL:
2067 		/* we can use 64bit DMA for the reqdma buffer */
2068 		err = usb_allocmem(sc->sc_bus.ub_dmatag,
2069 		    sizeof(usb_device_request_t), 0, USBMALLOC_COHERENT,
2070 		    &epipe->ctrl.reqdma);
2071 #ifdef EHCI_DEBUG
2072 		if (err)
2073 			printf("ehci_open: usb_allocmem()=%d\n", err);
2074 #endif
2075 		if (err)
2076 			goto bad;
2077 		pipe->up_methods = &ehci_device_ctrl_methods;
2078 		mutex_enter(&sc->sc_lock);
2079 		ehci_add_qh(sc, sqh, sc->sc_async_head);
2080 		mutex_exit(&sc->sc_lock);
2081 		break;
2082 	case UE_BULK:
2083 		pipe->up_methods = &ehci_device_bulk_methods;
2084 		mutex_enter(&sc->sc_lock);
2085 		ehci_add_qh(sc, sqh, sc->sc_async_head);
2086 		mutex_exit(&sc->sc_lock);
2087 		break;
2088 	case UE_INTERRUPT:
2089 		pipe->up_methods = &ehci_device_intr_methods;
2090 		ival = pipe->up_interval;
2091 		if (ival == USBD_DEFAULT_INTERVAL) {
2092 			if (speed == EHCI_QH_SPEED_HIGH) {
2093 				if (ed->bInterval > 16) {
2094 					/*
2095 					 * illegal with high-speed, but there
2096 					 * were documentation bugs in the spec,
2097 					 * so be generous
2098 					 */
2099 					ival = 256;
2100 				} else
2101 					ival = (1 << (ed->bInterval - 1)) / 8;
2102 			} else
2103 				ival = ed->bInterval;
2104 		}
2105 		err = ehci_device_setintr(sc, sqh, ival);
2106 		if (err)
2107 			goto bad;
2108 		break;
2109 	case UE_ISOCHRONOUS:
2110 		pipe->up_serialise = false;
2111 		if (speed == EHCI_QH_SPEED_HIGH)
2112 			pipe->up_methods = &ehci_device_isoc_methods;
2113 		else
2114 			pipe->up_methods = &ehci_device_fs_isoc_methods;
2115 		if (ed->bInterval == 0 || ed->bInterval > 16) {
2116 			printf("ehci: opening pipe with invalid bInterval\n");
2117 			err = USBD_INVAL;
2118 			goto bad;
2119 		}
2120 		if (UGETW(ed->wMaxPacketSize) == 0) {
2121 			printf("ehci: zero length endpoint open request\n");
2122 			err = USBD_INVAL;
2123 			goto bad;
2124 		}
2125 		epipe->isoc.next_frame = 0;
2126 		epipe->isoc.cur_xfers = 0;
2127 		break;
2128 	default:
2129 		DPRINTF("bad xfer type %jd", xfertype, 0, 0, 0);
2130 		err = USBD_INVAL;
2131 		goto bad;
2132 	}
2133 	return USBD_NORMAL_COMPLETION;
2134 
2135  bad:
2136 	if (sqh != NULL) {
2137 		mutex_enter(&sc->sc_lock);
2138 		ehci_free_sqh(sc, sqh);
2139 		mutex_exit(&sc->sc_lock);
2140 	}
2141 	return err;
2142 }
2143 
2144 /*
2145  * Add an ED to the schedule.  Called with USB lock held.
2146  */
2147 Static void
2148 ehci_add_qh(ehci_softc_t *sc, ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
2149 {
2150 
2151 	KASSERT(mutex_owned(&sc->sc_lock));
2152 
2153 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2154 
2155 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
2156 	    sizeof(head->qh.qh_link), BUS_DMASYNC_POSTWRITE);
2157 
2158 	sqh->next = head->next;
2159 	sqh->qh.qh_link = head->qh.qh_link;
2160 
2161 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
2162 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_PREWRITE);
2163 
2164 	head->next = sqh;
2165 	head->qh.qh_link = htole32(sqh->physaddr | EHCI_LINK_QH);
2166 
2167 	usb_syncmem(&head->dma, head->offs + offsetof(ehci_qh_t, qh_link),
2168 	    sizeof(head->qh.qh_link), BUS_DMASYNC_PREWRITE);
2169 
2170 #ifdef EHCI_DEBUG
2171 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
2172 	ehci_dump_sqh(sqh);
2173 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
2174 #endif
2175 }
2176 
2177 /*
2178  * Remove an ED from the schedule.  Called with USB lock held.
2179  */
2180 Static void
2181 ehci_rem_qh(ehci_softc_t *sc, ehci_soft_qh_t *sqh, ehci_soft_qh_t *head)
2182 {
2183 	ehci_soft_qh_t *p;
2184 
2185 	KASSERT(mutex_owned(&sc->sc_lock));
2186 
2187 	/* XXX */
2188 	for (p = head; p != NULL && p->next != sqh; p = p->next)
2189 		;
2190 	if (p == NULL)
2191 		panic("ehci_rem_qh: ED not found");
2192 	usb_syncmem(&sqh->dma, sqh->offs + offsetof(ehci_qh_t, qh_link),
2193 	    sizeof(sqh->qh.qh_link), BUS_DMASYNC_POSTWRITE);
2194 	p->next = sqh->next;
2195 	p->qh.qh_link = sqh->qh.qh_link;
2196 	usb_syncmem(&p->dma, p->offs + offsetof(ehci_qh_t, qh_link),
2197 	    sizeof(p->qh.qh_link), BUS_DMASYNC_PREWRITE);
2198 
2199 	ehci_sync_hc(sc);
2200 }
2201 
2202 Static void
2203 ehci_set_qh_qtd(ehci_soft_qh_t *sqh, ehci_soft_qtd_t *sqtd)
2204 {
2205 	int i;
2206 	uint32_t status;
2207 
2208 	/* Save toggle bit and ping status. */
2209 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
2210 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
2211 	status = sqh->qh.qh_qtd.qtd_status &
2212 	    htole32(EHCI_QTD_TOGGLE_MASK |
2213 		    EHCI_QTD_SET_STATUS(EHCI_QTD_PINGSTATE));
2214 	/* Set HALTED to make hw leave it alone. */
2215 	sqh->qh.qh_qtd.qtd_status =
2216 	    htole32(EHCI_QTD_SET_STATUS(EHCI_QTD_HALTED));
2217 	usb_syncmem(&sqh->dma,
2218 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
2219 	    sizeof(sqh->qh.qh_qtd.qtd_status),
2220 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2221 	sqh->qh.qh_curqtd = 0;
2222 	sqh->qh.qh_qtd.qtd_next = htole32(sqtd->physaddr);
2223 	sqh->qh.qh_qtd.qtd_altnext = EHCI_NULL;
2224 	for (i = 0; i < EHCI_QTD_NBUFFERS; i++)
2225 		sqh->qh.qh_qtd.qtd_buffer[i] = 0;
2226 	sqh->sqtd = sqtd;
2227 	usb_syncmem(&sqh->dma, sqh->offs, sizeof(sqh->qh),
2228 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2229 	/* Set !HALTED && !ACTIVE to start execution, preserve some fields */
2230 	sqh->qh.qh_qtd.qtd_status = status;
2231 	usb_syncmem(&sqh->dma,
2232 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
2233 	    sizeof(sqh->qh.qh_qtd.qtd_status),
2234 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2235 }
2236 
2237 /*
2238  * Ensure that the HC has released all references to the QH.  We do this
2239  * by asking for a Async Advance Doorbell interrupt and then we wait for
2240  * the interrupt.
2241  * To make this easier we first obtain exclusive use of the doorbell.
2242  *
2243  * Releases the bus lock to sleep while waiting for interrupt.
2244  */
2245 Static void
2246 ehci_sync_hc(ehci_softc_t *sc)
2247 {
2248 	unsigned delta = hz;
2249 	unsigned starttime = getticks();
2250 	unsigned endtime = starttime + delta;
2251 	unsigned now;
2252 
2253 	KASSERT(mutex_owned(&sc->sc_lock));
2254 
2255 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2256 
2257 	if (sc->sc_dying) {
2258 		DPRINTF("dying", 0, 0, 0, 0);
2259 		return;
2260 	}
2261 
2262 	/*
2263 	 * Wait until any concurrent ehci_sync_hc has completed so we
2264 	 * have exclusive access to the doorbell.
2265 	 */
2266 	while (sc->sc_doorbelllwp)
2267 		cv_wait(&sc->sc_doorbell, &sc->sc_lock);
2268 	sc->sc_doorbelllwp = curlwp;
2269 
2270 	/* ask for doorbell */
2271 	EOWRITE4(sc, EHCI_USBCMD, EOREAD4(sc, EHCI_USBCMD) | EHCI_CMD_IAAD);
2272 	DPRINTF("cmd = 0x%08jx sts = 0x%08jx",
2273 	    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS), 0, 0);
2274 
2275 	/*
2276 	 * Wait for the ehci to ring our doorbell.
2277 	 */
2278 	while (sc->sc_doorbelllwp == curlwp) {
2279 		now = getticks();
2280 		if (endtime - now > delta) {
2281 			sc->sc_doorbelllwp = NULL;
2282 			cv_signal(&sc->sc_doorbell);
2283 			DPRINTF("doorbell timeout", 0, 0, 0, 0);
2284 #ifdef DIAGNOSTIC		/* XXX DIAGNOSTIC abuse, do this differently */
2285 			printf("ehci_sync_hc: timed out\n");
2286 #endif
2287 			break;
2288 		}
2289 		(void)cv_timedwait(&sc->sc_doorbell, &sc->sc_lock,
2290 		    endtime - now);
2291 	}
2292 
2293 	DPRINTF("cmd = 0x%08jx sts = 0x%08jx ... done",
2294 	    EOREAD4(sc, EHCI_USBCMD), EOREAD4(sc, EHCI_USBSTS), 0, 0);
2295 }
2296 
2297 Static void
2298 ehci_remove_itd_chain(ehci_softc_t *sc, struct ehci_soft_itd *itd)
2299 {
2300 
2301 	KASSERT(mutex_owned(&sc->sc_lock));
2302 
2303 	for (; itd != NULL; itd = itd->xfer_next) {
2304 		struct ehci_soft_itd *prev = itd->frame_list.prev;
2305 
2306 		/* Unlink itd from hardware chain, or frame array */
2307 		if (prev == NULL) { /* We're at the table head */
2308 			sc->sc_softitds[itd->slot] = itd->frame_list.next;
2309 			sc->sc_flist[itd->slot] = itd->itd.itd_next;
2310 			usb_syncmem(&sc->sc_fldma,
2311 			    sizeof(ehci_link_t) * itd->slot,
2312 			    sizeof(ehci_link_t),
2313 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2314 
2315 			if (itd->frame_list.next != NULL)
2316 				itd->frame_list.next->frame_list.prev = NULL;
2317 		} else {
2318 			/* XXX this part is untested... */
2319 			prev->itd.itd_next = itd->itd.itd_next;
2320 			usb_syncmem(&itd->dma,
2321 			    itd->offs + offsetof(ehci_itd_t, itd_next),
2322 			    sizeof(itd->itd.itd_next), BUS_DMASYNC_PREWRITE);
2323 
2324 			prev->frame_list.next = itd->frame_list.next;
2325 			if (itd->frame_list.next != NULL)
2326 				itd->frame_list.next->frame_list.prev = prev;
2327 		}
2328 	}
2329 }
2330 
2331 Static void
2332 ehci_free_itd_chain(ehci_softc_t *sc, struct ehci_soft_itd *itd)
2333 {
2334 	struct ehci_soft_itd *next;
2335 
2336 	mutex_enter(&sc->sc_lock);
2337 	next = NULL;
2338 	for (; itd != NULL; itd = next) {
2339 		next = itd->xfer_next;
2340 		ehci_free_itd_locked(sc, itd);
2341 	}
2342 	mutex_exit(&sc->sc_lock);
2343 }
2344 
2345 Static void
2346 ehci_remove_sitd_chain(ehci_softc_t *sc, struct ehci_soft_sitd *sitd)
2347 {
2348 
2349 	KASSERT(mutex_owned(&sc->sc_lock));
2350 
2351 	for (; sitd != NULL; sitd = sitd->xfer_next) {
2352 		struct ehci_soft_sitd *prev = sitd->frame_list.prev;
2353 
2354 		/* Unlink sitd from hardware chain, or frame array */
2355 		if (prev == NULL) { /* We're at the table head */
2356 			sc->sc_softsitds[sitd->slot] = sitd->frame_list.next;
2357 			sc->sc_flist[sitd->slot] = sitd->sitd.sitd_next;
2358 			usb_syncmem(&sc->sc_fldma,
2359 			    sizeof(ehci_link_t) * sitd->slot,
2360 			    sizeof(ehci_link_t),
2361 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2362 
2363 			if (sitd->frame_list.next != NULL)
2364 				sitd->frame_list.next->frame_list.prev = NULL;
2365 		} else {
2366 			/* XXX this part is untested... */
2367 			prev->sitd.sitd_next = sitd->sitd.sitd_next;
2368 			usb_syncmem(&sitd->dma,
2369 			    sitd->offs + offsetof(ehci_sitd_t, sitd_next),
2370 			    sizeof(sitd->sitd.sitd_next), BUS_DMASYNC_PREWRITE);
2371 
2372 			prev->frame_list.next = sitd->frame_list.next;
2373 			if (sitd->frame_list.next != NULL)
2374 				sitd->frame_list.next->frame_list.prev = prev;
2375 		}
2376 	}
2377 }
2378 
2379 Static void
2380 ehci_free_sitd_chain(ehci_softc_t *sc, struct ehci_soft_sitd *sitd)
2381 {
2382 
2383 	mutex_enter(&sc->sc_lock);
2384 	struct ehci_soft_sitd *next  = NULL;
2385 	for (; sitd != NULL; sitd = next) {
2386 		next = sitd->xfer_next;
2387 		ehci_free_sitd_locked(sc, sitd);
2388 	}
2389 	mutex_exit(&sc->sc_lock);
2390 }
2391 
2392 /***********/
2393 
2394 static int
2395 ehci_roothub_ctrl_locked(struct usbd_bus *bus, usb_device_request_t *req,
2396     void *buf, int buflen)
2397 {
2398 	ehci_softc_t *sc = EHCI_BUS2SC(bus);
2399 	usb_hub_descriptor_t hubd;
2400 	usb_port_status_t ps;
2401 	uint16_t len, value, index;
2402 	int l, totlen = 0;
2403 	int port, i;
2404 	uint32_t v;
2405 
2406 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2407 
2408 	KASSERT(mutex_owned(&sc->sc_rhlock));
2409 
2410 	if (sc->sc_dying)
2411 		return -1;
2412 
2413 	DPRINTF("type=0x%02jx request=%02jx", req->bmRequestType, req->bRequest,
2414 	    0, 0);
2415 
2416 	len = UGETW(req->wLength);
2417 	value = UGETW(req->wValue);
2418 	index = UGETW(req->wIndex);
2419 
2420 #define C(x,y) ((x) | ((y) << 8))
2421 	switch (C(req->bRequest, req->bmRequestType)) {
2422 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2423 		if (len == 0)
2424 			break;
2425 		switch (value) {
2426 #define sd ((usb_string_descriptor_t *)buf)
2427 		case C(2, UDESC_STRING):
2428 			/* Product */
2429 			totlen = usb_makestrdesc(sd, len, "EHCI root hub");
2430 			break;
2431 #undef sd
2432 		default:
2433 			/* default from usbroothub */
2434 			return buflen;
2435 		}
2436 		break;
2437 
2438 	/* Hub requests */
2439 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2440 		break;
2441 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2442 		DPRINTF("UR_CLEAR_PORT_FEATURE port=%jd feature=%jd", index,
2443 		    value, 0, 0);
2444 		if (index < 1 || index > sc->sc_noport) {
2445 			return -1;
2446 		}
2447 		port = EHCI_PORTSC(index);
2448 		v = EOREAD4(sc, port);
2449 		DPRINTF("portsc=0x%08jx", v, 0, 0, 0);
2450 		v &= ~EHCI_PS_CLEAR;
2451 		switch (value) {
2452 		case UHF_PORT_ENABLE:
2453 			EOWRITE4(sc, port, v &~ EHCI_PS_PE);
2454 			break;
2455 		case UHF_PORT_SUSPEND:
2456 			if (!(v & EHCI_PS_SUSP)) /* not suspended */
2457 				break;
2458 			v &= ~EHCI_PS_SUSP;
2459 			EOWRITE4(sc, port, v | EHCI_PS_FPR);
2460 			/* see USB2 spec ch. 7.1.7.7 */
2461 			usb_delay_ms(&sc->sc_bus, 20);
2462 			EOWRITE4(sc, port, v);
2463 			usb_delay_ms(&sc->sc_bus, 2);
2464 #ifdef DEBUG
2465 			v = EOREAD4(sc, port);
2466 			if (v & (EHCI_PS_FPR | EHCI_PS_SUSP))
2467 				printf("ehci: resume failed: %x\n", v);
2468 #endif
2469 			break;
2470 		case UHF_PORT_POWER:
2471 			if (sc->sc_hasppc)
2472 				EOWRITE4(sc, port, v &~ EHCI_PS_PP);
2473 			break;
2474 		case UHF_PORT_TEST:
2475 			DPRINTF("clear port test %jd", index, 0, 0, 0);
2476 			break;
2477 		case UHF_PORT_INDICATOR:
2478 			DPRINTF("clear port ind %jd", index, 0, 0, 0);
2479 			EOWRITE4(sc, port, v &~ EHCI_PS_PIC);
2480 			break;
2481 		case UHF_C_PORT_CONNECTION:
2482 			EOWRITE4(sc, port, v | EHCI_PS_CSC);
2483 			break;
2484 		case UHF_C_PORT_ENABLE:
2485 			EOWRITE4(sc, port, v | EHCI_PS_PEC);
2486 			break;
2487 		case UHF_C_PORT_SUSPEND:
2488 			/* how? */
2489 			break;
2490 		case UHF_C_PORT_OVER_CURRENT:
2491 			EOWRITE4(sc, port, v | EHCI_PS_OCC);
2492 			break;
2493 		case UHF_C_PORT_RESET:
2494 			sc->sc_isreset[index] = 0;
2495 			break;
2496 		default:
2497 			return -1;
2498 		}
2499 #if 0
2500 		switch(value) {
2501 		case UHF_C_PORT_CONNECTION:
2502 		case UHF_C_PORT_ENABLE:
2503 		case UHF_C_PORT_SUSPEND:
2504 		case UHF_C_PORT_OVER_CURRENT:
2505 		case UHF_C_PORT_RESET:
2506 		default:
2507 			break;
2508 		}
2509 #endif
2510 		break;
2511 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2512 		if (len == 0)
2513 			break;
2514 		if ((value & 0xff) != 0) {
2515 			return -1;
2516 		}
2517 		totlen = uimin(buflen, sizeof(hubd));
2518 		memcpy(&hubd, buf, totlen);
2519 		hubd.bNbrPorts = sc->sc_noport;
2520 		v = EREAD4(sc, EHCI_HCSPARAMS);
2521 		USETW(hubd.wHubCharacteristics,
2522 		    (EHCI_HCS_PPC(v) ? UHD_PWR_INDIVIDUAL : UHD_PWR_NO_SWITCH) |
2523 		    (EHCI_HCS_P_INDICATOR(v) ? UHD_PORT_IND : 0));
2524 		hubd.bPwrOn2PwrGood = 200; /* XXX can't find out? */
2525 		for (i = 0, l = sc->sc_noport; l > 0; i++, l -= 8, v >>= 8)
2526 			hubd.DeviceRemovable[i++] = 0; /* XXX can't find out? */
2527 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
2528 		totlen = uimin(totlen, hubd.bDescLength);
2529 		memcpy(buf, &hubd, totlen);
2530 		break;
2531 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2532 		if (len != 4) {
2533 			return -1;
2534 		}
2535 		memset(buf, 0, len); /* ? XXX */
2536 		totlen = len;
2537 		break;
2538 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2539 		DPRINTF("get port status i=%jd", index, 0, 0, 0);
2540 		if (index < 1 || index > sc->sc_noport) {
2541 			return -1;
2542 		}
2543 		if (len != 4) {
2544 			return -1;
2545 		}
2546 		v = EOREAD4(sc, EHCI_PORTSC(index));
2547 		DPRINTF("port status=0x%04jx", v, 0, 0, 0);
2548 
2549 		i = UPS_HIGH_SPEED;
2550 		if (sc->sc_flags & EHCIF_ETTF) {
2551 			/*
2552 			 * If we are doing embedded transaction translation,
2553 			 * then directly attached LS/FS devices are reset by
2554 			 * the EHCI controller itself.  PSPD is encoded
2555 			 * the same way as in USBSTATUS.
2556 			 */
2557 			i = __SHIFTOUT(v, EHCI_PS_PSPD) * UPS_LOW_SPEED;
2558 		}
2559 		if (v & EHCI_PS_CS)	i |= UPS_CURRENT_CONNECT_STATUS;
2560 		if (v & EHCI_PS_PE)	i |= UPS_PORT_ENABLED;
2561 		if (v & EHCI_PS_SUSP)	i |= UPS_SUSPEND;
2562 		if (v & EHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
2563 		if (v & EHCI_PS_PR)	i |= UPS_RESET;
2564 		if (v & EHCI_PS_PP)	i |= UPS_PORT_POWER;
2565 		if (sc->sc_vendor_port_status)
2566 			i = sc->sc_vendor_port_status(sc, v, i);
2567 		USETW(ps.wPortStatus, i);
2568 		i = 0;
2569 		if (v & EHCI_PS_CSC)	i |= UPS_C_CONNECT_STATUS;
2570 		if (v & EHCI_PS_PEC)	i |= UPS_C_PORT_ENABLED;
2571 		if (v & EHCI_PS_OCC)	i |= UPS_C_OVERCURRENT_INDICATOR;
2572 		if (sc->sc_isreset[index]) i |= UPS_C_PORT_RESET;
2573 		USETW(ps.wPortChange, i);
2574 		totlen = uimin(len, sizeof(ps));
2575 		memcpy(buf, &ps, totlen);
2576 		break;
2577 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2578 		return -1;
2579 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2580 		break;
2581 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2582 		if (index < 1 || index > sc->sc_noport) {
2583 			return -1;
2584 		}
2585 		port = EHCI_PORTSC(index);
2586 		v = EOREAD4(sc, port);
2587 		DPRINTF("portsc=0x%08jx", v, 0, 0, 0);
2588 		v &= ~EHCI_PS_CLEAR;
2589 		switch(value) {
2590 		case UHF_PORT_ENABLE:
2591 			EOWRITE4(sc, port, v | EHCI_PS_PE);
2592 			break;
2593 		case UHF_PORT_SUSPEND:
2594 			EOWRITE4(sc, port, v | EHCI_PS_SUSP);
2595 			break;
2596 		case UHF_PORT_RESET:
2597 			DPRINTF("reset port %jd", index, 0, 0, 0);
2598 			if (EHCI_PS_IS_LOWSPEED(v)
2599 			    && sc->sc_ncomp > 0
2600 			    && !(sc->sc_flags & EHCIF_ETTF)) {
2601 				/*
2602 				 * Low speed device on non-ETTF controller or
2603 				 * unaccompanied controller, give up ownership.
2604 				 */
2605 				ehci_disown(sc, index, 1);
2606 				break;
2607 			}
2608 			/* Start reset sequence. */
2609 			v &= ~ (EHCI_PS_PE | EHCI_PS_PR);
2610 			EOWRITE4(sc, port, v | EHCI_PS_PR);
2611 			/* Wait for reset to complete. */
2612 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
2613 			if (sc->sc_dying) {
2614 				return -1;
2615 			}
2616 			/*
2617 			 * An embedded transaction translator will automatically
2618 			 * terminate the reset sequence so there's no need to
2619 			 * it.
2620 			 */
2621 			v = EOREAD4(sc, port);
2622 			if (v & EHCI_PS_PR) {
2623 				/* Terminate reset sequence. */
2624 				EOWRITE4(sc, port, v & ~EHCI_PS_PR);
2625 				/* Wait for HC to complete reset. */
2626 				usb_delay_ms(&sc->sc_bus,
2627 				    EHCI_PORT_RESET_COMPLETE);
2628 				if (sc->sc_dying) {
2629 					return -1;
2630 				}
2631 			}
2632 
2633 			v = EOREAD4(sc, port);
2634 			DPRINTF("ehci after reset, status=0x%08jx", v, 0, 0, 0);
2635 			if (v & EHCI_PS_PR) {
2636 				printf("%s: port reset timeout\n",
2637 				       device_xname(sc->sc_dev));
2638 				return USBD_TIMEOUT;
2639 			}
2640 			if (!(v & EHCI_PS_PE)) {
2641 				/* Not a high speed device, give up ownership.*/
2642 				ehci_disown(sc, index, 0);
2643 				break;
2644 			}
2645 			sc->sc_isreset[index] = 1;
2646 			DPRINTF("ehci port %jd reset, status = 0x%08jx", index,
2647 			    v, 0, 0);
2648 			break;
2649 		case UHF_PORT_POWER:
2650 			DPRINTF("set port power %jd (has PPC = %jd)", index,
2651 			    sc->sc_hasppc, 0, 0);
2652 			if (sc->sc_hasppc)
2653 				EOWRITE4(sc, port, v | EHCI_PS_PP);
2654 			break;
2655 		case UHF_PORT_TEST:
2656 			DPRINTF("set port test %jd", index, 0, 0, 0);
2657 			break;
2658 		case UHF_PORT_INDICATOR:
2659 			DPRINTF("set port ind %jd", index, 0, 0, 0);
2660 			EOWRITE4(sc, port, v | EHCI_PS_PIC);
2661 			break;
2662 		default:
2663 			return -1;
2664 		}
2665 		break;
2666 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
2667 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
2668 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
2669 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
2670 		break;
2671 	default:
2672 		/* default from usbroothub */
2673 		DPRINTF("returning %jd (usbroothub default)", buflen, 0, 0, 0);
2674 
2675 		return buflen;
2676 	}
2677 
2678 	DPRINTF("returning %jd", totlen, 0, 0, 0);
2679 
2680 	return totlen;
2681 }
2682 
2683 Static int
2684 ehci_roothub_ctrl(struct usbd_bus *bus, usb_device_request_t *req,
2685     void *buf, int buflen)
2686 {
2687 	struct ehci_softc *sc = EHCI_BUS2SC(bus);
2688 	int actlen;
2689 
2690 	mutex_enter(&sc->sc_rhlock);
2691 	actlen = ehci_roothub_ctrl_locked(bus, req, buf, buflen);
2692 	mutex_exit(&sc->sc_rhlock);
2693 
2694 	return actlen;
2695 }
2696 
2697 /*
2698  * Handle ehci hand-off in early boot vs RB_ASKNAME/RB_SINGLE.
2699  *
2700  * This pile of garbage below works around the following problem without
2701  * holding boots with no hand-over devices present, while penalising
2702  * boots where the first ehci probe hands off devices with a 5 second
2703  * delay, if RB_ASKNAME/RB_SINGLE is set.  This is typically not a problem
2704  * for RB_SINGLE, but the same basic issue exists.
2705  *
2706  * The way ehci hand-off works, the companion controller does not get the
2707  * device until after its initial bus explore, so the reference dropped
2708  * after the first explore is not enough.  5 seconds should be enough,
2709  * and EHCI_DISOWN_DELAY_SECONDS can be set to another value.
2710  *
2711  * There are 3 states.  CO_EARLY is set during attach.  CO_SCHED is set
2712  * if the callback is scheduled.  CO_DONE is set when the callout has
2713  * called config_pending_decr().
2714  *
2715  * There's a mutex, a cv and a callout here, and we delay detach if the
2716  * callout has been set.
2717  */
2718 #ifndef EHCI_DISOWN_DELAY_SECONDS
2719 #define EHCI_DISOWN_DELAY_SECONDS 5
2720 #endif
2721 static int ehci_disown_delay_seconds = EHCI_DISOWN_DELAY_SECONDS;
2722 
2723 static void
2724 ehci_disown_callback(void *arg)
2725 {
2726 	ehci_softc_t *sc = arg;
2727 
2728 	config_pending_decr(sc->sc_dev);
2729 
2730 	mutex_enter(&sc->sc_complock);
2731 	KASSERT(sc->sc_comp_state == CO_SCHED);
2732 	sc->sc_comp_state = CO_DONE;
2733 	cv_signal(&sc->sc_compcv);
2734 	mutex_exit(&sc->sc_complock);
2735 }
2736 
2737 static void
2738 ehci_disown_sched_callback(ehci_softc_t *sc)
2739 {
2740 	extern bool root_is_mounted;
2741 
2742 	mutex_enter(&sc->sc_complock);
2743 
2744 	if (root_is_mounted ||
2745 	    (boothowto & (RB_ASKNAME|RB_SINGLE)) == 0 ||
2746 	    sc->sc_comp_state != CO_EARLY) {
2747 		mutex_exit(&sc->sc_complock);
2748 		return;
2749 	}
2750 
2751 	callout_reset(&sc->sc_compcallout, ehci_disown_delay_seconds * hz,
2752 	    ehci_disown_callback, &sc->sc_dev);
2753 	sc->sc_comp_state = CO_SCHED;
2754 
2755 	mutex_exit(&sc->sc_complock);
2756 
2757 	config_pending_incr(sc->sc_dev);
2758 	aprint_normal_dev(sc->sc_dev,
2759 	    "delaying %s by %u seconds due to USB owner change.\n",
2760 	    (boothowto & RB_ASKNAME) != 0 ? "ask root" : "single user",
2761 	    ehci_disown_delay_seconds);
2762 }
2763 
2764 Static void
2765 ehci_disown(ehci_softc_t *sc, int index, int lowspeed)
2766 {
2767 	int port;
2768 	uint32_t v;
2769 
2770 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2771 
2772 	DPRINTF("index=%jd lowspeed=%jd", index, lowspeed, 0, 0);
2773 	if (sc->sc_npcomp != 0) {
2774 		int i = (index-1) / sc->sc_npcomp;
2775 		if (i < sc->sc_ncomp) {
2776 			ehci_disown_sched_callback(sc);
2777 #ifdef DIAGNOSTIC
2778 			printf("%s: handing over %s speed device on "
2779 			       "port %d to %s\n",
2780 			       device_xname(sc->sc_dev),
2781 			       lowspeed ? "low" : "full",
2782 			       index, sc->sc_comps[i] ?
2783 			         device_xname(sc->sc_comps[i]) :
2784 			         "companion controller");
2785 		} else {
2786 			printf("%s: strange port\n",
2787 			       device_xname(sc->sc_dev));
2788 #endif
2789 		}
2790 	} else {
2791 #ifdef DIAGNOSTIC
2792 		printf("%s: npcomp == 0\n", device_xname(sc->sc_dev));
2793 #endif
2794 	}
2795 	port = EHCI_PORTSC(index);
2796 	v = EOREAD4(sc, port) &~ EHCI_PS_CLEAR;
2797 	EOWRITE4(sc, port, v | EHCI_PS_PO);
2798 }
2799 
2800 Static usbd_status
2801 ehci_root_intr_transfer(struct usbd_xfer *xfer)
2802 {
2803 
2804 	/* Pipe isn't running, start first */
2805 	return ehci_root_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
2806 }
2807 
2808 Static usbd_status
2809 ehci_root_intr_start(struct usbd_xfer *xfer)
2810 {
2811 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
2812 
2813 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
2814 
2815 	if (sc->sc_dying)
2816 		return USBD_IOERROR;
2817 
2818 	KASSERT(sc->sc_intrxfer == NULL);
2819 	sc->sc_intrxfer = xfer;
2820 	xfer->ux_status = USBD_IN_PROGRESS;
2821 
2822 	return USBD_IN_PROGRESS;
2823 }
2824 
2825 /* Abort a root interrupt request. */
2826 Static void
2827 ehci_root_intr_abort(struct usbd_xfer *xfer)
2828 {
2829 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
2830 
2831 	KASSERT(mutex_owned(&sc->sc_lock));
2832 	KASSERT(xfer->ux_pipe->up_intrxfer == xfer);
2833 
2834 	/* If xfer has already completed, nothing to do here.  */
2835 	if (sc->sc_intrxfer == NULL)
2836 		return;
2837 
2838 	/*
2839 	 * Otherwise, sc->sc_intrxfer had better be this transfer.
2840 	 * Cancel it.
2841 	 */
2842 	KASSERT(sc->sc_intrxfer == xfer);
2843 	KASSERT(xfer->ux_status == USBD_IN_PROGRESS);
2844 	xfer->ux_status = USBD_CANCELLED;
2845 	usb_transfer_complete(xfer);
2846 }
2847 
2848 /* Close the root pipe. */
2849 Static void
2850 ehci_root_intr_close(struct usbd_pipe *pipe)
2851 {
2852 	ehci_softc_t *sc __diagused = EHCI_PIPE2SC(pipe);
2853 
2854 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2855 
2856 	KASSERT(mutex_owned(&sc->sc_lock));
2857 
2858 	/*
2859 	 * Caller must guarantee the xfer has completed first, by
2860 	 * closing the pipe only after normal completion or an abort.
2861 	 */
2862 	KASSERT(sc->sc_intrxfer == NULL);
2863 }
2864 
2865 Static void
2866 ehci_root_intr_done(struct usbd_xfer *xfer)
2867 {
2868 	struct ehci_softc *sc = EHCI_XFER2SC(xfer);
2869 
2870 	KASSERT(mutex_owned(&sc->sc_lock));
2871 
2872 	/* Claim the xfer so it doesn't get completed again.  */
2873 	KASSERT(sc->sc_intrxfer == xfer);
2874 	KASSERT(xfer->ux_status != USBD_IN_PROGRESS);
2875 	sc->sc_intrxfer = NULL;
2876 }
2877 
2878 /************************/
2879 
2880 Static ehci_soft_qh_t *
2881 ehci_alloc_sqh(ehci_softc_t *sc)
2882 {
2883 	ehci_soft_qh_t *sqh;
2884 
2885 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2886 
2887 	mutex_enter(&sc->sc_lock);
2888 	if (sc->sc_freeqhs == NULL) {
2889 		DPRINTF("allocating chunk", 0, 0, 0, 0);
2890 		mutex_exit(&sc->sc_lock);
2891 
2892 		usb_dma_t dma;
2893 		int err = usb_allocmem(sc->sc_dmatag,
2894 		    EHCI_SQH_SIZE * EHCI_SQH_CHUNK,
2895 		    EHCI_PAGE_SIZE, USBMALLOC_COHERENT, &dma);
2896 
2897 		if (err) {
2898 			DPRINTF("alloc returned %jd", err, 0, 0, 0);
2899 			return NULL;
2900 		}
2901 
2902 		mutex_enter(&sc->sc_lock);
2903 		for (size_t i = 0; i < EHCI_SQH_CHUNK; i++) {
2904 			const int offs = i * EHCI_SQH_SIZE;
2905 			const bus_addr_t baddr = DMAADDR(&dma, offs);
2906 
2907 			KASSERT(BUS_ADDR_HI32(baddr) == 0);
2908 
2909 			sqh = KERNADDR(&dma, offs);
2910 			sqh->physaddr = BUS_ADDR_LO32(baddr);
2911 			sqh->dma = dma;
2912 			sqh->offs = offs;
2913 
2914 			sqh->next = sc->sc_freeqhs;
2915 			sc->sc_freeqhs = sqh;
2916 		}
2917 	}
2918 	sqh = sc->sc_freeqhs;
2919 	sc->sc_freeqhs = sqh->next;
2920 	mutex_exit(&sc->sc_lock);
2921 
2922 	memset(&sqh->qh, 0, sizeof(ehci_qh_t));
2923 	sqh->next = NULL;
2924 	return sqh;
2925 }
2926 
2927 Static void
2928 ehci_free_sqh(ehci_softc_t *sc, ehci_soft_qh_t *sqh)
2929 {
2930 	KASSERT(mutex_owned(&sc->sc_lock));
2931 
2932 	sqh->next = sc->sc_freeqhs;
2933 	sc->sc_freeqhs = sqh;
2934 }
2935 
2936 Static ehci_soft_qtd_t *
2937 ehci_alloc_sqtd(ehci_softc_t *sc)
2938 {
2939 	ehci_soft_qtd_t *sqtd = NULL;
2940 
2941 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
2942 
2943 	mutex_enter(&sc->sc_lock);
2944 	if (sc->sc_freeqtds == NULL) {
2945 		DPRINTF("allocating chunk", 0, 0, 0, 0);
2946 		mutex_exit(&sc->sc_lock);
2947 
2948 		usb_dma_t dma;
2949 		int err = usb_allocmem(sc->sc_dmatag,
2950 		    EHCI_SQTD_SIZE * EHCI_SQTD_CHUNK,
2951 		    EHCI_PAGE_SIZE, USBMALLOC_COHERENT, &dma);
2952 
2953 		if (err) {
2954 			DPRINTF("alloc returned %jd", err, 0, 0, 0);
2955 			return NULL;
2956 		}
2957 
2958 		mutex_enter(&sc->sc_lock);
2959 		for (size_t i = 0; i < EHCI_SQTD_CHUNK; i++) {
2960 			const int offs = i * EHCI_SQTD_SIZE;
2961 			const bus_addr_t baddr = DMAADDR(&dma, offs);
2962 
2963 			KASSERT(BUS_ADDR_HI32(baddr) == 0);
2964 
2965 			sqtd = KERNADDR(&dma, offs);
2966 			sqtd->physaddr = BUS_ADDR_LO32(baddr);
2967 			sqtd->dma = dma;
2968 			sqtd->offs = offs;
2969 
2970 			sqtd->nextqtd = sc->sc_freeqtds;
2971 			sc->sc_freeqtds = sqtd;
2972 		}
2973 	}
2974 
2975 	sqtd = sc->sc_freeqtds;
2976 	sc->sc_freeqtds = sqtd->nextqtd;
2977 	mutex_exit(&sc->sc_lock);
2978 
2979 	memset(&sqtd->qtd, 0, sizeof(ehci_qtd_t));
2980 	sqtd->nextqtd = NULL;
2981 	sqtd->xfer = NULL;
2982 
2983 	return sqtd;
2984 }
2985 
2986 Static void
2987 ehci_free_sqtd(ehci_softc_t *sc, ehci_soft_qtd_t *sqtd)
2988 {
2989 
2990 	mutex_enter(&sc->sc_lock);
2991 	sqtd->nextqtd = sc->sc_freeqtds;
2992 	sc->sc_freeqtds = sqtd;
2993 	mutex_exit(&sc->sc_lock);
2994 }
2995 
2996 Static int
2997 ehci_alloc_sqtd_chain(ehci_softc_t *sc, struct usbd_xfer *xfer,
2998     int alen, int rd, ehci_soft_qtd_t **sp)
2999 {
3000 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3001 	uint16_t flags = xfer->ux_flags;
3002 
3003 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3004 
3005 	ASSERT_SLEEPABLE();
3006 	KASSERT(sp);
3007 	KASSERT(alen != 0 || (!rd && (flags & USBD_FORCE_SHORT_XFER)));
3008 
3009 	size_t nsqtd = (!rd && (flags & USBD_FORCE_SHORT_XFER)) ? 1 : 0;
3010 	nsqtd += howmany(alen, EHCI_PAGE_SIZE);
3011 	exfer->ex_sqtds = kmem_zalloc(sizeof(ehci_soft_qtd_t *) * nsqtd,
3012 	    KM_SLEEP);
3013 	exfer->ex_nsqtd = nsqtd;
3014 
3015 	DPRINTF("xfer %#jx len %jd nsqtd %jd flags %jx", (uintptr_t)xfer,
3016 	    alen, nsqtd, flags);
3017 
3018 	for (size_t j = 0; j < exfer->ex_nsqtd;) {
3019 		ehci_soft_qtd_t *cur = ehci_alloc_sqtd(sc);
3020 		if (cur == NULL)
3021 			goto nomem;
3022 		exfer->ex_sqtds[j++] = cur;
3023 
3024 		cur->xfer = xfer;
3025 		cur->len = 0;
3026 
3027 	}
3028 
3029 	*sp = exfer->ex_sqtds[0];
3030 	DPRINTF("return sqtd=%#jx", (uintptr_t)*sp, 0, 0, 0);
3031 
3032 	return 0;
3033 
3034  nomem:
3035 	ehci_free_sqtds(sc, exfer);
3036 	kmem_free(exfer->ex_sqtds, sizeof(ehci_soft_qtd_t *) * nsqtd);
3037 	DPRINTF("no memory", 0, 0, 0, 0);
3038 	return ENOMEM;
3039 }
3040 
3041 Static void
3042 ehci_free_sqtds(ehci_softc_t *sc, struct ehci_xfer *exfer)
3043 {
3044 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3045 	DPRINTF("exfer=%#jx", (uintptr_t)exfer, 0, 0, 0);
3046 
3047 	mutex_enter(&sc->sc_lock);
3048 	for (size_t i = 0; i < exfer->ex_nsqtd; i++) {
3049 		ehci_soft_qtd_t *sqtd = exfer->ex_sqtds[i];
3050 
3051 		if (sqtd == NULL)
3052 			break;
3053 
3054 		sqtd->nextqtd = sc->sc_freeqtds;
3055 		sc->sc_freeqtds = sqtd;
3056 	}
3057 	mutex_exit(&sc->sc_lock);
3058 }
3059 
3060 Static void
3061 ehci_append_sqtd(ehci_soft_qtd_t *sqtd, ehci_soft_qtd_t *prev)
3062 {
3063 	if (prev) {
3064 		prev->nextqtd = sqtd;
3065 		prev->qtd.qtd_next = htole32(sqtd->physaddr);
3066 		prev->qtd.qtd_altnext = prev->qtd.qtd_next;
3067 		usb_syncmem(&prev->dma, prev->offs, sizeof(prev->qtd),
3068 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3069 	}
3070 }
3071 
3072 Static void
3073 ehci_reset_sqtd_chain(ehci_softc_t *sc, struct usbd_xfer *xfer,
3074     int length, int isread, int *toggle, ehci_soft_qtd_t **lsqtd)
3075 {
3076 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3077 	usb_dma_t *dma = &xfer->ux_dmabuf;
3078 	uint16_t flags = xfer->ux_flags;
3079 	ehci_soft_qtd_t *sqtd, *prev;
3080 	int tog = *toggle;
3081 	int mps = UGETW(xfer->ux_pipe->up_endpoint->ue_edesc->wMaxPacketSize);
3082 	int len = length;
3083 
3084 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3085 	DPRINTF("xfer=%#jx len %jd isread %jd toggle %jd", (uintptr_t)xfer,
3086 	    len, isread, tog);
3087 	DPRINTF("    VA %#jx", (uintptr_t)KERNADDR(&xfer->ux_dmabuf, 0),
3088 	    0, 0, 0);
3089 
3090 	KASSERT(length != 0 || (!isread && (flags & USBD_FORCE_SHORT_XFER)));
3091 
3092 	const uint32_t qtdstatus = EHCI_QTD_ACTIVE |
3093 	    EHCI_QTD_SET_PID(isread ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT) |
3094 	    EHCI_QTD_SET_CERR(3)
3095 	    ;
3096 
3097 	sqtd = prev = NULL;
3098 	size_t curoffs = 0;
3099 	size_t j = 0;
3100 	for (; len != 0 && j < exfer->ex_nsqtd; prev = sqtd) {
3101 		sqtd = exfer->ex_sqtds[j++];
3102 		DPRINTF("sqtd[%jd]=%#jx prev %#jx", j, (uintptr_t)sqtd,
3103 		    (uintptr_t)prev, 0);
3104 
3105 		/*
3106 		 * The EHCI hardware can handle at most 5 pages and they do
3107 		 * not have to be contiguous
3108 		 */
3109 		vaddr_t va = (vaddr_t)KERNADDR(dma, curoffs);
3110 		vaddr_t va_offs = EHCI_PAGE_OFFSET(va);
3111 		size_t curlen = len;
3112 		if (curlen >= EHCI_QTD_MAXTRANSFER - va_offs) {
3113 			/* must use multiple TDs, fill as much as possible. */
3114 			curlen = EHCI_QTD_MAXTRANSFER - va_offs;
3115 
3116 			/* the length must be a multiple of the max size */
3117 			curlen -= curlen % mps;
3118 		}
3119 		KASSERT(curlen != 0);
3120 		DPRINTF("    len=%jd curlen=%jd curoffs=%ju", len, curlen,
3121 		    curoffs, 0);
3122 
3123 		/* Fill the qTD */
3124 		sqtd->qtd.qtd_next = sqtd->qtd.qtd_altnext = EHCI_NULL;
3125 		sqtd->qtd.qtd_status = htole32(
3126 		    qtdstatus |
3127 		    EHCI_QTD_SET_BYTES(curlen) |
3128 		    EHCI_QTD_SET_TOGGLE(tog));
3129 
3130 		/* Find number of pages we'll be using, insert dma addresses */
3131 		size_t pages = EHCI_NPAGES(curlen);
3132 		KASSERT(pages <= EHCI_QTD_NBUFFERS);
3133 		size_t pageoffs = EHCI_PAGE(curoffs);
3134 		for (size_t i = 0; i < pages; i++) {
3135 			paddr_t a = EHCI_PAGE(DMAADDR(dma,
3136 			    pageoffs + i * EHCI_PAGE_SIZE));
3137 			sqtd->qtd.qtd_buffer[i] = htole32(BUS_ADDR_LO32(a));
3138 			sqtd->qtd.qtd_buffer_hi[i] = htole32(BUS_ADDR_HI32(a));
3139 			DPRINTF("      buffer[%jd/%jd] 0x%08jx 0x%08jx",
3140 			    i, pages,
3141 			    le32toh(sqtd->qtd.qtd_buffer_hi[i]),
3142 			    le32toh(sqtd->qtd.qtd_buffer[i]));
3143 		}
3144 		/* First buffer pointer requires a page offset to start at */
3145 		sqtd->qtd.qtd_buffer[0] |= htole32(va_offs);
3146 
3147 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
3148 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3149 
3150 		sqtd->len = curlen;
3151 
3152 		DPRINTF("    va %#jx pa %#jx len %jd", (uintptr_t)va,
3153 		    (uintptr_t)DMAADDR(&xfer->ux_dmabuf, curoffs), curlen, 0);
3154 
3155 		ehci_append_sqtd(sqtd, prev);
3156 
3157 		if (howmany(curlen, mps) & 1) {
3158 			tog ^= 1;
3159 		}
3160 
3161 		curoffs += curlen;
3162 		len -= curlen;
3163 	}
3164 	KASSERTMSG(len == 0, "xfer %p olen %d len %d mps %d ex_nsqtd %zu j %zu",
3165 	    xfer, length, len, mps, exfer->ex_nsqtd, j);
3166 
3167 	if (!isread &&
3168 	    (flags & USBD_FORCE_SHORT_XFER) &&
3169 	    length % mps == 0) {
3170 		/* Force a 0 length transfer at the end. */
3171 
3172 		KASSERTMSG(j < exfer->ex_nsqtd, "j=%zu nsqtd=%zu", j,
3173 		    exfer->ex_nsqtd);
3174 		prev = sqtd;
3175 		sqtd = exfer->ex_sqtds[j++];
3176 		memset(&sqtd->qtd, 0, sizeof(sqtd->qtd));
3177 		sqtd->qtd.qtd_next = sqtd->qtd.qtd_altnext = EHCI_NULL;
3178 		sqtd->qtd.qtd_status = htole32(
3179 		    qtdstatus |
3180 		    EHCI_QTD_SET_BYTES(0) |
3181 		    EHCI_QTD_SET_TOGGLE(tog));
3182 
3183 		usb_syncmem(&sqtd->dma, sqtd->offs, sizeof(sqtd->qtd),
3184 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3185 
3186 		ehci_append_sqtd(sqtd, prev);
3187 		tog ^= 1;
3188 	}
3189 
3190 	*lsqtd = sqtd;
3191 	*toggle = tog;
3192 }
3193 
3194 Static ehci_soft_itd_t *
3195 ehci_alloc_itd(ehci_softc_t *sc)
3196 {
3197 	struct ehci_soft_itd *itd, *freeitd;
3198 
3199 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3200 
3201 	mutex_enter(&sc->sc_lock);
3202 
3203 	freeitd = LIST_FIRST(&sc->sc_freeitds);
3204 	if (freeitd == NULL) {
3205 		DPRINTF("allocating chunk", 0, 0, 0, 0);
3206 		mutex_exit(&sc->sc_lock);
3207 
3208 		usb_dma_t dma;
3209 		int err = usb_allocmem(sc->sc_dmatag,
3210 		    EHCI_ITD_SIZE * EHCI_ITD_CHUNK,
3211 		    EHCI_PAGE_SIZE, USBMALLOC_COHERENT, &dma);
3212 
3213 		if (err) {
3214 			DPRINTF("alloc returned %jd", err, 0, 0, 0);
3215 			return NULL;
3216 		}
3217 
3218 		mutex_enter(&sc->sc_lock);
3219 		for (size_t i = 0; i < EHCI_ITD_CHUNK; i++) {
3220 			const int offs = i * EHCI_ITD_SIZE;
3221 			const bus_addr_t baddr = DMAADDR(&dma, offs);
3222 
3223 			KASSERT(BUS_ADDR_HI32(baddr) == 0);
3224 
3225 			itd = KERNADDR(&dma, offs);
3226 			itd->physaddr = BUS_ADDR_LO32(baddr);
3227 	 		itd->dma = dma;
3228 			itd->offs = offs;
3229 
3230 			LIST_INSERT_HEAD(&sc->sc_freeitds, itd, free_list);
3231 		}
3232 		freeitd = LIST_FIRST(&sc->sc_freeitds);
3233 	}
3234 
3235 	itd = freeitd;
3236 	LIST_REMOVE(itd, free_list);
3237 	mutex_exit(&sc->sc_lock);
3238 	memset(&itd->itd, 0, sizeof(ehci_itd_t));
3239 
3240 	itd->frame_list.next = NULL;
3241 	itd->frame_list.prev = NULL;
3242 	itd->xfer_next = NULL;
3243 	itd->slot = 0;
3244 
3245 	return itd;
3246 }
3247 
3248 Static ehci_soft_sitd_t *
3249 ehci_alloc_sitd(ehci_softc_t *sc)
3250 {
3251 	struct ehci_soft_sitd *sitd, *freesitd;
3252 
3253 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3254 
3255 	mutex_enter(&sc->sc_lock);
3256 	freesitd = LIST_FIRST(&sc->sc_freesitds);
3257 	if (freesitd == NULL) {
3258 		DPRINTF("allocating chunk", 0, 0, 0, 0);
3259 		mutex_exit(&sc->sc_lock);
3260 
3261 		usb_dma_t dma;
3262 		int err = usb_allocmem(sc->sc_dmatag,
3263 		    EHCI_SITD_SIZE * EHCI_SITD_CHUNK,
3264 		    EHCI_PAGE_SIZE, USBMALLOC_COHERENT, &dma);
3265 
3266 		if (err) {
3267 			DPRINTF("alloc returned %jd", err, 0, 0, 0);
3268 			return NULL;
3269 		}
3270 
3271 		mutex_enter(&sc->sc_lock);
3272 		for (size_t i = 0; i < EHCI_SITD_CHUNK; i++) {
3273 			const int offs = i * EHCI_SITD_SIZE;
3274 			const bus_addr_t baddr = DMAADDR(&dma, offs);
3275 
3276 			KASSERT(BUS_ADDR_HI32(baddr) == 0);
3277 
3278 			sitd = KERNADDR(&dma, offs);
3279 			sitd->physaddr = BUS_ADDR_LO32(baddr);
3280 	 		sitd->dma = dma;
3281 			sitd->offs = offs;
3282 
3283 			LIST_INSERT_HEAD(&sc->sc_freesitds, sitd, free_list);
3284 		}
3285 		freesitd = LIST_FIRST(&sc->sc_freesitds);
3286 	}
3287 
3288 	sitd = freesitd;
3289 	LIST_REMOVE(sitd, free_list);
3290 	mutex_exit(&sc->sc_lock);
3291 
3292 	memset(&sitd->sitd, 0, sizeof(ehci_sitd_t));
3293 
3294 	sitd->frame_list.next = NULL;
3295 	sitd->frame_list.prev = NULL;
3296 	sitd->xfer_next = NULL;
3297 	sitd->slot = 0;
3298 
3299 	return sitd;
3300 }
3301 
3302 /****************/
3303 
3304 /*
3305  * Close a reqular pipe.
3306  * Assumes that there are no pending transactions.
3307  */
3308 Static void
3309 ehci_close_pipe(struct usbd_pipe *pipe, ehci_soft_qh_t *head)
3310 {
3311 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(pipe);
3312 	ehci_softc_t *sc = EHCI_PIPE2SC(pipe);
3313 	ehci_soft_qh_t *sqh = epipe->sqh;
3314 
3315 	KASSERT(mutex_owned(&sc->sc_lock));
3316 
3317 	ehci_rem_qh(sc, sqh, head);
3318 	ehci_free_sqh(sc, epipe->sqh);
3319 }
3320 
3321 /*
3322  * Arrange for the hardware to tells us that it is not still
3323  * processing the TDs by setting the QH halted bit and wait for the ehci
3324  * door bell
3325  */
3326 Static void
3327 ehci_abortx(struct usbd_xfer *xfer)
3328 {
3329 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3330 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
3331 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3332 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3333 	ehci_soft_qh_t *sqh = epipe->sqh;
3334 	ehci_soft_qtd_t *sqtd, *fsqtd, *lsqtd;
3335 	ehci_physaddr_t cur;
3336 	uint32_t qhstatus;
3337 	int hit;
3338 
3339 	DPRINTF("xfer=%#jx pipe=%#jx", (uintptr_t)xfer, (uintptr_t)epipe, 0, 0);
3340 
3341 	KASSERT(mutex_owned(&sc->sc_lock));
3342 	ASSERT_SLEEPABLE();
3343 
3344 	KASSERTMSG((xfer->ux_status == USBD_CANCELLED ||
3345 		xfer->ux_status == USBD_TIMEOUT),
3346 	    "bad abort status: %d", xfer->ux_status);
3347 
3348 	/*
3349 	 * If we're dying, skip the hardware action and just notify the
3350 	 * software that we're done.
3351 	 */
3352 	if (sc->sc_dying) {
3353 		goto dying;
3354 	}
3355 
3356 	/*
3357 	 * HC Step 1: Make interrupt routine and hardware ignore xfer.
3358 	 */
3359 	ehci_del_intr_list(sc, exfer);
3360 
3361 	usb_syncmem(&sqh->dma,
3362 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3363 	    sizeof(sqh->qh.qh_qtd.qtd_status),
3364 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3365 	qhstatus = sqh->qh.qh_qtd.qtd_status;
3366 	sqh->qh.qh_qtd.qtd_status = qhstatus | htole32(EHCI_QTD_HALTED);
3367 	usb_syncmem(&sqh->dma,
3368 	    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3369 	    sizeof(sqh->qh.qh_qtd.qtd_status),
3370 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3371 
3372 	if (exfer->ex_type == EX_CTRL) {
3373 		fsqtd = exfer->ex_setup;
3374 		lsqtd = exfer->ex_status;
3375 	} else {
3376 		fsqtd = exfer->ex_sqtdstart;
3377 		lsqtd = exfer->ex_sqtdend;
3378 	}
3379 	for (sqtd = fsqtd; ; sqtd = sqtd->nextqtd) {
3380 		usb_syncmem(&sqtd->dma,
3381 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
3382 		    sizeof(sqtd->qtd.qtd_status),
3383 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3384 		sqtd->qtd.qtd_status |= htole32(EHCI_QTD_HALTED);
3385 		usb_syncmem(&sqtd->dma,
3386 		    sqtd->offs + offsetof(ehci_qtd_t, qtd_status),
3387 		    sizeof(sqtd->qtd.qtd_status),
3388 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3389 		if (sqtd == lsqtd)
3390 			break;
3391 	}
3392 
3393 	/*
3394 	 * HC Step 2: Wait until we know hardware has finished any possible
3395 	 * use of the xfer.
3396 	 */
3397 	ehci_sync_hc(sc);
3398 
3399 	/*
3400 	 * HC Step 3: Remove any vestiges of the xfer from the hardware.
3401 	 * The complication here is that the hardware may have executed
3402 	 * beyond the xfer we're trying to abort.  So as we're scanning
3403 	 * the TDs of this xfer we check if the hardware points to
3404 	 * any of them.
3405 	 */
3406 
3407 	usb_syncmem(&sqh->dma,
3408 	    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
3409 	    sizeof(sqh->qh.qh_curqtd),
3410 	    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3411 	cur = EHCI_LINK_ADDR(le32toh(sqh->qh.qh_curqtd));
3412 	hit = 0;
3413 	for (sqtd = fsqtd; ; sqtd = sqtd->nextqtd) {
3414 		hit |= cur == sqtd->physaddr;
3415 		if (sqtd == lsqtd)
3416 			break;
3417 	}
3418 	sqtd = sqtd->nextqtd;
3419 	/* Zap curqtd register if hardware pointed inside the xfer. */
3420 	if (hit && sqtd != NULL) {
3421 		DPRINTF("cur=0x%08jx", sqtd->physaddr, 0, 0, 0);
3422 		sqh->qh.qh_curqtd = htole32(sqtd->physaddr); /* unlink qTDs */
3423 		usb_syncmem(&sqh->dma,
3424 		    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
3425 		    sizeof(sqh->qh.qh_curqtd),
3426 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3427 		sqh->qh.qh_qtd.qtd_status = qhstatus;
3428 		usb_syncmem(&sqh->dma,
3429 		    sqh->offs + offsetof(ehci_qh_t, qh_qtd.qtd_status),
3430 		    sizeof(sqh->qh.qh_qtd.qtd_status),
3431 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3432 	} else {
3433 		DPRINTF("no hit", 0, 0, 0, 0);
3434 		usb_syncmem(&sqh->dma,
3435 		    sqh->offs + offsetof(ehci_qh_t, qh_curqtd),
3436 		    sizeof(sqh->qh.qh_curqtd),
3437 		    BUS_DMASYNC_PREREAD);
3438 	}
3439 
3440 dying:
3441 #ifdef DIAGNOSTIC
3442 	exfer->ex_isdone = true;
3443 #endif
3444 	DPRINTFN(14, "end", 0, 0, 0, 0);
3445 
3446 	KASSERT(mutex_owned(&sc->sc_lock));
3447 }
3448 
3449 Static void
3450 ehci_abort_isoc_xfer(struct usbd_xfer *xfer, usbd_status status)
3451 {
3452 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3453 	ehci_isoc_trans_t trans_status;
3454 	struct ehci_xfer *exfer;
3455 	ehci_softc_t *sc;
3456 	struct ehci_soft_itd *itd;
3457 	struct ehci_soft_sitd *sitd;
3458 	int i;
3459 
3460 	KASSERTMSG(status == USBD_CANCELLED,
3461 	    "invalid status for abort: %d", (int)status);
3462 
3463 	exfer = EHCI_XFER2EXFER(xfer);
3464 	sc = EHCI_XFER2SC(xfer);
3465 
3466 	DPRINTF("xfer %#jx pipe %#jx", (uintptr_t)xfer,
3467 	    (uintptr_t)xfer->ux_pipe, 0, 0);
3468 
3469 	KASSERT(mutex_owned(&sc->sc_lock));
3470 	ASSERT_SLEEPABLE();
3471 
3472 	/* No timeout or task here. */
3473 
3474 	/*
3475 	 * The xfer cannot have been cancelled already.  It is the
3476 	 * responsibility of the caller of usbd_abort_pipe not to try
3477 	 * to abort a pipe multiple times, whether concurrently or
3478 	 * sequentially.
3479 	 */
3480 	KASSERT(xfer->ux_status != USBD_CANCELLED);
3481 
3482 	/* If anyone else beat us, we're done.  */
3483 	if (xfer->ux_status != USBD_IN_PROGRESS)
3484 		return;
3485 
3486 	/* We beat everyone else.  Claim the status.  */
3487 	xfer->ux_status = status;
3488 
3489 	/*
3490 	 * If we're dying, skip the hardware action and just notify the
3491 	 * software that we're done.
3492 	 */
3493 	if (sc->sc_dying) {
3494 		goto dying;
3495 	}
3496 
3497 	/*
3498 	 * HC Step 1: Make interrupt routine and hardware ignore xfer.
3499 	 */
3500 	ehci_del_intr_list(sc, exfer);
3501 
3502 	if (xfer->ux_pipe->up_dev->ud_speed == USB_SPEED_HIGH) {
3503 		for (itd = exfer->ex_itdstart; itd != NULL;
3504 		     itd = itd->xfer_next) {
3505 			usb_syncmem(&itd->dma,
3506 			    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3507 			    sizeof(itd->itd.itd_ctl),
3508 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3509 
3510 			for (i = 0; i < 8; i++) {
3511 				trans_status = le32toh(itd->itd.itd_ctl[i]);
3512 				trans_status &= ~EHCI_ITD_ACTIVE;
3513 				itd->itd.itd_ctl[i] = htole32(trans_status);
3514 			}
3515 
3516 			usb_syncmem(&itd->dma,
3517 			    itd->offs + offsetof(ehci_itd_t, itd_ctl),
3518 			    sizeof(itd->itd.itd_ctl),
3519 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3520 		}
3521 	} else {
3522 		for (sitd = exfer->ex_sitdstart; sitd != NULL;
3523 		     sitd = sitd->xfer_next) {
3524 			usb_syncmem(&sitd->dma,
3525 			    sitd->offs + offsetof(ehci_sitd_t, sitd_buffer),
3526 			    sizeof(sitd->sitd.sitd_buffer),
3527 			    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
3528 
3529 			trans_status = le32toh(sitd->sitd.sitd_trans);
3530 			trans_status &= ~EHCI_SITD_ACTIVE;
3531 			sitd->sitd.sitd_trans = htole32(trans_status);
3532 
3533 			usb_syncmem(&sitd->dma,
3534 			    sitd->offs + offsetof(ehci_sitd_t, sitd_buffer),
3535 			    sizeof(sitd->sitd.sitd_buffer),
3536 			    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3537 		}
3538 	}
3539 
3540 dying:
3541 #ifdef DIAGNOSTIC
3542 	exfer->ex_isdone = true;
3543 #endif
3544 	usb_transfer_complete(xfer);
3545 	DPRINTFN(14, "end", 0, 0, 0, 0);
3546 
3547 	KASSERT(mutex_owned(&sc->sc_lock));
3548 }
3549 
3550 /************************/
3551 
3552 Static int
3553 ehci_device_ctrl_init(struct usbd_xfer *xfer)
3554 {
3555 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3556 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
3557 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3558 	usb_device_request_t *req = &xfer->ux_request;
3559 	ehci_soft_qtd_t *setup, *status, *next;
3560 	int isread = req->bmRequestType & UT_READ;
3561 	int len = xfer->ux_bufsize;
3562 	int err;
3563 
3564 	exfer->ex_type = EX_CTRL;
3565 	exfer->ex_status = NULL;
3566 	exfer->ex_data = NULL;
3567 	exfer->ex_setup = ehci_alloc_sqtd(sc);
3568 	if (exfer->ex_setup == NULL) {
3569 		err = ENOMEM;
3570 		goto bad1;
3571 	}
3572 	exfer->ex_status = ehci_alloc_sqtd(sc);
3573 	if (exfer->ex_status == NULL) {
3574 		err = ENOMEM;
3575 		goto bad2;
3576 	}
3577 	setup = exfer->ex_setup;
3578 	status = exfer->ex_status;
3579 	exfer->ex_nsqtd = 0;
3580 	next = status;
3581 	/* Set up data transaction */
3582 	if (len != 0) {
3583 		err = ehci_alloc_sqtd_chain(sc, xfer, len, isread,
3584 		    &exfer->ex_data);
3585 		if (err)
3586 			goto bad3;
3587 		next = exfer->ex_data;
3588 	}
3589 
3590 	/* Clear toggle */
3591 	setup->qtd.qtd_status = htole32(
3592 	    EHCI_QTD_SET_PID(EHCI_QTD_PID_SETUP) |
3593 	    EHCI_QTD_SET_TOGGLE(0) |
3594 	    EHCI_QTD_SET_BYTES(sizeof(*req))
3595 	    );
3596 
3597 	const bus_addr_t ba = DMAADDR(&epipe->ctrl.reqdma, 0);
3598 	setup->qtd.qtd_buffer[0] = htole32(BUS_ADDR_LO32(ba));
3599 	setup->qtd.qtd_buffer_hi[0] = htole32(BUS_ADDR_HI32(ba));
3600 	setup->qtd.qtd_next = setup->qtd.qtd_altnext = htole32(next->physaddr);
3601 	setup->nextqtd = next;
3602 	setup->xfer = xfer;
3603 	setup->len = sizeof(*req);
3604 
3605 	status->qtd.qtd_status = htole32(
3606 	    EHCI_QTD_SET_PID(isread ? EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN) |
3607 	    EHCI_QTD_SET_TOGGLE(1) |
3608 	    EHCI_QTD_IOC
3609 	    );
3610 	status->qtd.qtd_buffer[0] = 0;
3611 	status->qtd.qtd_buffer_hi[0] = 0;
3612 	status->qtd.qtd_next = status->qtd.qtd_altnext = EHCI_NULL;
3613 	status->nextqtd = NULL;
3614 	status->xfer = xfer;
3615 	status->len = 0;
3616 
3617 	return 0;
3618 bad3:
3619 	ehci_free_sqtd(sc, exfer->ex_status);
3620 bad2:
3621 	ehci_free_sqtd(sc, exfer->ex_setup);
3622 bad1:
3623 	return err;
3624 }
3625 
3626 Static void
3627 ehci_device_ctrl_fini(struct usbd_xfer *xfer)
3628 {
3629 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3630 	struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
3631 
3632 	KASSERT(ex->ex_type == EX_CTRL);
3633 
3634 	ehci_free_sqtd(sc, ex->ex_setup);
3635 	ehci_free_sqtd(sc, ex->ex_status);
3636 	ehci_free_sqtds(sc, ex);
3637 	if (ex->ex_nsqtd)
3638 		kmem_free(ex->ex_sqtds,
3639 		    sizeof(ehci_soft_qtd_t *) * ex->ex_nsqtd);
3640 }
3641 
3642 Static usbd_status
3643 ehci_device_ctrl_transfer(struct usbd_xfer *xfer)
3644 {
3645 
3646 	/* Pipe isn't running, start first */
3647 	return ehci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3648 }
3649 
3650 Static usbd_status
3651 ehci_device_ctrl_start(struct usbd_xfer *xfer)
3652 {
3653 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
3654 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3655 	usb_device_request_t *req = &xfer->ux_request;
3656 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3657 	ehci_soft_qtd_t *setup, *status, *next;
3658 	ehci_soft_qh_t *sqh;
3659 
3660 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3661 
3662 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
3663 	KASSERT(xfer->ux_rqflags & URQ_REQUEST);
3664 
3665 	if (sc->sc_dying)
3666 		return USBD_IOERROR;
3667 
3668 	const int isread = req->bmRequestType & UT_READ;
3669 	const int len = UGETW(req->wLength);
3670 
3671 	DPRINTF("type=0x%02jx, request=0x%02jx, wValue=0x%04jx, wIndex=0x%04jx",
3672 	    req->bmRequestType, req->bRequest, UGETW(req->wValue),
3673 	    UGETW(req->wIndex));
3674 	DPRINTF("len=%jd, addr=%jd, endpt=%jd",
3675 	    len, epipe->pipe.up_dev->ud_addr,
3676 	    epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress, 0);
3677 
3678 	sqh = epipe->sqh;
3679 
3680 	KASSERTMSG(EHCI_QH_GET_ADDR(le32toh(sqh->qh.qh_endp)) == epipe->pipe.up_dev->ud_addr,
3681 	    "address QH %" __PRIuBIT " pipe %d\n",
3682 	    EHCI_QH_GET_ADDR(le32toh(sqh->qh.qh_endp)),
3683 	    epipe->pipe.up_dev->ud_addr);
3684 	KASSERTMSG(EHCI_QH_GET_MPL(le32toh(sqh->qh.qh_endp)) ==
3685 	    UGETW(epipe->pipe.up_endpoint->ue_edesc->wMaxPacketSize),
3686 	    "MPS QH %" __PRIuBIT " pipe %d\n",
3687 	    EHCI_QH_GET_MPL(le32toh(sqh->qh.qh_endp)),
3688 	    UGETW(epipe->pipe.up_endpoint->ue_edesc->wMaxPacketSize));
3689 
3690 	setup = exfer->ex_setup;
3691 	status = exfer->ex_status;
3692 
3693 	DPRINTF("setup %#jx status %#jx data %#jx",
3694 	    (uintptr_t)setup, (uintptr_t)status, (uintptr_t)exfer->ex_data, 0);
3695 	KASSERTMSG(setup != NULL && status != NULL,
3696 	    "Failed memory allocation, setup %p status %p",
3697 	    setup, status);
3698 
3699 	memcpy(KERNADDR(&epipe->ctrl.reqdma, 0), req, sizeof(*req));
3700 	usb_syncmem(&epipe->ctrl.reqdma, 0, sizeof(*req), BUS_DMASYNC_PREWRITE);
3701 
3702 	/* Clear toggle */
3703 	setup->qtd.qtd_status &= ~htole32(
3704 	    EHCI_QTD_STATUS_MASK |
3705 	    EHCI_QTD_BYTES_MASK |
3706 	    EHCI_QTD_TOGGLE_MASK |
3707 	    EHCI_QTD_CERR_MASK
3708 	    );
3709 	setup->qtd.qtd_status |= htole32(
3710 	    EHCI_QTD_ACTIVE |
3711 	    EHCI_QTD_SET_CERR(3) |
3712 	    EHCI_QTD_SET_TOGGLE(0) |
3713 	    EHCI_QTD_SET_BYTES(sizeof(*req))
3714 	    );
3715 
3716 	const bus_addr_t ba = DMAADDR(&epipe->ctrl.reqdma, 0);
3717 	setup->qtd.qtd_buffer[0] = htole32(BUS_ADDR_LO32(ba));
3718 	setup->qtd.qtd_buffer_hi[0] = htole32(BUS_ADDR_HI32(ba));
3719 
3720 	next = status;
3721 	status->qtd.qtd_status &= ~htole32(
3722 	    EHCI_QTD_STATUS_MASK |
3723 	    EHCI_QTD_PID_MASK |
3724 	    EHCI_QTD_BYTES_MASK |
3725 	    EHCI_QTD_TOGGLE_MASK |
3726 	    EHCI_QTD_CERR_MASK
3727 	    );
3728 	status->qtd.qtd_status |= htole32(
3729 	    EHCI_QTD_ACTIVE |
3730 	    EHCI_QTD_SET_PID(isread ? EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN) |
3731 	    EHCI_QTD_SET_CERR(3) |
3732 	    EHCI_QTD_SET_TOGGLE(1) |
3733 	    EHCI_QTD_SET_BYTES(0) |
3734 	    EHCI_QTD_IOC
3735 	    );
3736 	KASSERT(status->qtd.qtd_status & htole32(EHCI_QTD_TOGGLE_MASK));
3737 
3738 	KASSERT(exfer->ex_isdone);
3739 #ifdef DIAGNOSTIC
3740 	exfer->ex_isdone = false;
3741 #endif
3742 
3743 	/* Set up data transaction */
3744 	if (len != 0) {
3745 		ehci_soft_qtd_t *end;
3746 
3747 		/* Start toggle at 1. */
3748 		int toggle = 1;
3749 		next = exfer->ex_data;
3750 		KASSERTMSG(next != NULL, "Failed memory allocation");
3751 		ehci_reset_sqtd_chain(sc, xfer, len, isread, &toggle, &end);
3752 		end->nextqtd = status;
3753 		end->qtd.qtd_next = end->qtd.qtd_altnext =
3754 		    htole32(status->physaddr);
3755 
3756 		usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
3757 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3758 
3759 		usb_syncmem(&xfer->ux_dmabuf, 0, len,
3760 		    isread ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
3761 	}
3762 
3763 	setup->nextqtd = next;
3764 	setup->qtd.qtd_next = setup->qtd.qtd_altnext = htole32(next->physaddr);
3765 
3766 	usb_syncmem(&setup->dma, setup->offs, sizeof(setup->qtd),
3767 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3768 
3769 	 usb_syncmem(&status->dma, status->offs, sizeof(status->qtd),
3770 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3771 
3772 	KASSERT(status->qtd.qtd_status & htole32(EHCI_QTD_TOGGLE_MASK));
3773 
3774 #ifdef EHCI_DEBUG
3775 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
3776 	ehci_dump_sqh(sqh);
3777 	ehci_dump_sqtds(setup);
3778 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
3779 #endif
3780 
3781 	/* Insert qTD in QH list - also does usb_syncmem(sqh) */
3782 	ehci_set_qh_qtd(sqh, setup);
3783 	usbd_xfer_schedule_timeout(xfer);
3784 	ehci_add_intr_list(sc, exfer);
3785 	xfer->ux_status = USBD_IN_PROGRESS;
3786 
3787 #if 0
3788 #ifdef EHCI_DEBUG
3789 	DPRINTFN(10, "status=%jx, dump:", EOREAD4(sc, EHCI_USBSTS), 0, 0, 0);
3790 //	delay(10000);
3791 	ehci_dump_regs(sc);
3792 	ehci_dump_sqh(sc->sc_async_head);
3793 	ehci_dump_sqh(sqh);
3794 	ehci_dump_sqtds(setup);
3795 #endif
3796 #endif
3797 
3798 	return USBD_IN_PROGRESS;
3799 }
3800 
3801 Static void
3802 ehci_device_ctrl_done(struct usbd_xfer *xfer)
3803 {
3804 	ehci_softc_t *sc __diagused = EHCI_XFER2SC(xfer);
3805 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
3806 	usb_device_request_t *req = &xfer->ux_request;
3807 	int len = UGETW(req->wLength);
3808 	int rd = req->bmRequestType & UT_READ;
3809 
3810 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3811 	DPRINTF("xfer=%#jx", (uintptr_t)xfer, 0, 0, 0);
3812 
3813 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
3814 	KASSERT(xfer->ux_rqflags & URQ_REQUEST);
3815 
3816 	usb_syncmem(&epipe->ctrl.reqdma, 0, sizeof(*req),
3817 	    BUS_DMASYNC_POSTWRITE);
3818 	if (len)
3819 		usb_syncmem(&xfer->ux_dmabuf, 0, len,
3820 		    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3821 
3822 	DPRINTF("length=%jd", xfer->ux_actlen, 0, 0, 0);
3823 }
3824 
3825 /* Abort a device control request. */
3826 Static void
3827 ehci_device_ctrl_abort(struct usbd_xfer *xfer)
3828 {
3829 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3830 
3831 	DPRINTF("xfer=%#jx", (uintptr_t)xfer, 0, 0, 0);
3832 	usbd_xfer_abort(xfer);
3833 }
3834 
3835 /* Close a device control pipe. */
3836 Static void
3837 ehci_device_ctrl_close(struct usbd_pipe *pipe)
3838 {
3839 	ehci_softc_t *sc = EHCI_PIPE2SC(pipe);
3840 	struct ehci_pipe * const epipe = EHCI_PIPE2EPIPE(pipe);
3841 
3842 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3843 
3844 	KASSERT(mutex_owned(&sc->sc_lock));
3845 
3846 	DPRINTF("pipe=%#jx", (uintptr_t)pipe, 0, 0, 0);
3847 
3848 	ehci_close_pipe(pipe, sc->sc_async_head);
3849 
3850 	usb_freemem(&epipe->ctrl.reqdma);
3851 }
3852 
3853 /*
3854  * Some EHCI chips from VIA seem to trigger interrupts before writing back the
3855  * qTD status, or miss signalling occasionally under heavy load.  If the host
3856  * machine is too fast, we can miss transaction completion - when we scan
3857  * the active list the transaction still seems to be active.  This generally
3858  * exhibits itself as a umass stall that never recovers.
3859  *
3860  * We work around this behaviour by setting up this callback after any softintr
3861  * that completes with transactions still pending, giving us another chance to
3862  * check for completion after the writeback has taken place.
3863  */
3864 Static void
3865 ehci_intrlist_timeout(void *arg)
3866 {
3867 	ehci_softc_t *sc = arg;
3868 
3869 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3870 
3871 	usb_schedsoftintr(&sc->sc_bus);
3872 }
3873 
3874 /************************/
3875 
3876 Static int
3877 ehci_device_bulk_init(struct usbd_xfer *xfer)
3878 {
3879 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3880 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3881 	usb_endpoint_descriptor_t *ed = xfer->ux_pipe->up_endpoint->ue_edesc;
3882 	int endpt = ed->bEndpointAddress;
3883 	int isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3884 	int len = xfer->ux_bufsize;
3885 	int err = 0;
3886 
3887 	exfer->ex_type = EX_BULK;
3888 	exfer->ex_nsqtd = 0;
3889 	err = ehci_alloc_sqtd_chain(sc, xfer, len, isread,
3890 	    &exfer->ex_sqtdstart);
3891 
3892 	return err;
3893 }
3894 
3895 Static void
3896 ehci_device_bulk_fini(struct usbd_xfer *xfer)
3897 {
3898 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3899 	struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
3900 
3901 	KASSERT(ex->ex_type == EX_BULK);
3902 
3903 	ehci_free_sqtds(sc, ex);
3904 	if (ex->ex_nsqtd)
3905 		kmem_free(ex->ex_sqtds, sizeof(ehci_soft_qtd_t *) * ex->ex_nsqtd);
3906 }
3907 
3908 Static usbd_status
3909 ehci_device_bulk_transfer(struct usbd_xfer *xfer)
3910 {
3911 
3912 	/* Pipe isn't running, start first */
3913 	return ehci_device_bulk_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3914 }
3915 
3916 Static usbd_status
3917 ehci_device_bulk_start(struct usbd_xfer *xfer)
3918 {
3919 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
3920 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
3921 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
3922 	ehci_soft_qh_t *sqh;
3923 	ehci_soft_qtd_t *end;
3924 	int len, isread, endpt;
3925 
3926 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3927 
3928 	DPRINTF("xfer=%#jx len=%jd flags=%jd", (uintptr_t)xfer, xfer->ux_length,
3929 	    xfer->ux_flags, 0);
3930 
3931 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
3932 
3933 	if (sc->sc_dying)
3934 		return USBD_IOERROR;
3935 
3936 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
3937 	KASSERT(xfer->ux_length <= xfer->ux_bufsize);
3938 
3939 	len = xfer->ux_length;
3940 	endpt = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
3941 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
3942 	sqh = epipe->sqh;
3943 
3944 	KASSERT(exfer->ex_isdone);
3945 #ifdef DIAGNOSTIC
3946 	exfer->ex_isdone = false;
3947 #endif
3948 
3949 	ehci_reset_sqtd_chain(sc, xfer, len, isread, &epipe->nexttoggle, &end);
3950 
3951 	exfer->ex_sqtdend = end;
3952 	end->qtd.qtd_status |= htole32(EHCI_QTD_IOC);
3953 	usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
3954 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
3955 
3956 #ifdef EHCI_DEBUG
3957 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
3958 	ehci_dump_sqh(sqh);
3959 	ehci_dump_sqtds(exfer->ex_sqtdstart);
3960 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
3961 #endif
3962 
3963 	if (xfer->ux_length)
3964 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
3965 		    isread ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
3966 
3967 	/* also does usb_syncmem(sqh) */
3968 	ehci_set_qh_qtd(sqh, exfer->ex_sqtdstart);
3969 	usbd_xfer_schedule_timeout(xfer);
3970 	ehci_add_intr_list(sc, exfer);
3971 	xfer->ux_status = USBD_IN_PROGRESS;
3972 
3973 #if 0
3974 #ifdef EHCI_DEBUG
3975 	DPRINTFN(5, "data(2)", 0, 0, 0, 0);
3976 //	delay(10000);
3977 	DPRINTFN(5, "data(3)", 0, 0, 0, 0);
3978 	ehci_dump_regs(sc);
3979 #if 0
3980 	printf("async_head:\n");
3981 	ehci_dump_sqh(sc->sc_async_head);
3982 #endif
3983 	DPRINTF("sqh:", 0, 0, 0, 0);
3984 	ehci_dump_sqh(sqh);
3985 	ehci_dump_sqtds(exfer->ex_sqtdstart);
3986 #endif
3987 #endif
3988 
3989 	return USBD_IN_PROGRESS;
3990 }
3991 
3992 Static void
3993 ehci_device_bulk_abort(struct usbd_xfer *xfer)
3994 {
3995 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
3996 
3997 	DPRINTF("xfer %#jx", (uintptr_t)xfer, 0, 0, 0);
3998 	usbd_xfer_abort(xfer);
3999 }
4000 
4001 /*
4002  * Close a device bulk pipe.
4003  */
4004 Static void
4005 ehci_device_bulk_close(struct usbd_pipe *pipe)
4006 {
4007 	ehci_softc_t *sc = EHCI_PIPE2SC(pipe);
4008 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(pipe);
4009 
4010 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4011 
4012 	KASSERT(mutex_owned(&sc->sc_lock));
4013 
4014 	DPRINTF("pipe=%#jx", (uintptr_t)pipe, 0, 0, 0);
4015 	pipe->up_endpoint->ue_toggle = epipe->nexttoggle;
4016 	ehci_close_pipe(pipe, sc->sc_async_head);
4017 }
4018 
4019 Static void
4020 ehci_device_bulk_done(struct usbd_xfer *xfer)
4021 {
4022 	ehci_softc_t *sc __diagused = EHCI_XFER2SC(xfer);
4023 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4024 	int endpt = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4025 	int rd = UE_GET_DIR(endpt) == UE_DIR_IN;
4026 
4027 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4028 
4029 	DPRINTF("xfer=%#jx, actlen=%jd", (uintptr_t)xfer, xfer->ux_actlen, 0, 0);
4030 
4031 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
4032 
4033 	if (xfer->ux_length)
4034 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4035 		    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
4036 
4037 	DPRINTF("length=%jd", xfer->ux_actlen, 0, 0, 0);
4038 }
4039 
4040 /************************/
4041 
4042 Static usbd_status
4043 ehci_device_setintr(ehci_softc_t *sc, ehci_soft_qh_t *sqh, int ival)
4044 {
4045 	struct ehci_soft_islot *isp;
4046 	int islot, lev;
4047 
4048 	/* Find a poll rate that is large enough. */
4049 	for (lev = EHCI_IPOLLRATES - 1; lev > 0; lev--)
4050 		if (EHCI_ILEV_IVAL(lev) <= ival)
4051 			break;
4052 
4053 	/* Pick an interrupt slot at the right level. */
4054 	/* XXX could do better than picking at random */
4055 	sc->sc_rand = (sc->sc_rand + 191) % sc->sc_flsize;
4056 	islot = EHCI_IQHIDX(lev, sc->sc_rand);
4057 
4058 	sqh->islot = islot;
4059 	isp = &sc->sc_islots[islot];
4060 	mutex_enter(&sc->sc_lock);
4061 	ehci_add_qh(sc, sqh, isp->sqh);
4062 	mutex_exit(&sc->sc_lock);
4063 
4064 	return USBD_NORMAL_COMPLETION;
4065 }
4066 
4067 Static int
4068 ehci_device_intr_init(struct usbd_xfer *xfer)
4069 {
4070 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4071 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4072 	usb_endpoint_descriptor_t *ed = xfer->ux_pipe->up_endpoint->ue_edesc;
4073 	int endpt = ed->bEndpointAddress;
4074 	int isread = UE_GET_DIR(endpt) == UE_DIR_IN;
4075 	int len = xfer->ux_bufsize;
4076 	int err;
4077 
4078 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4079 
4080 	DPRINTF("xfer=%#jx len=%jd flags=%jd", (uintptr_t)xfer, xfer->ux_length,
4081 	    xfer->ux_flags, 0);
4082 
4083 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4084 	KASSERT(len != 0);
4085 
4086 	exfer->ex_type = EX_INTR;
4087 	exfer->ex_nsqtd = 0;
4088 	err = ehci_alloc_sqtd_chain(sc, xfer, len, isread,
4089 	    &exfer->ex_sqtdstart);
4090 
4091 	return err;
4092 }
4093 
4094 Static void
4095 ehci_device_intr_fini(struct usbd_xfer *xfer)
4096 {
4097 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4098 	struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
4099 
4100 	KASSERT(ex->ex_type == EX_INTR);
4101 
4102 	ehci_free_sqtds(sc, ex);
4103 	if (ex->ex_nsqtd)
4104 		kmem_free(ex->ex_sqtds, sizeof(ehci_soft_qtd_t *) * ex->ex_nsqtd);
4105 }
4106 
4107 Static usbd_status
4108 ehci_device_intr_transfer(struct usbd_xfer *xfer)
4109 {
4110 
4111 	/* Pipe isn't running, so start it first.  */
4112 	return ehci_device_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
4113 }
4114 
4115 Static usbd_status
4116 ehci_device_intr_start(struct usbd_xfer *xfer)
4117 {
4118 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4119 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4120 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4121 	ehci_soft_qtd_t *end;
4122 	ehci_soft_qh_t *sqh;
4123 	int len, isread, endpt;
4124 
4125 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4126 
4127 	DPRINTF("xfer=%#jx len=%jd flags=%jd", (uintptr_t)xfer, xfer->ux_length,
4128 	    xfer->ux_flags, 0);
4129 
4130 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
4131 
4132 	if (sc->sc_dying)
4133 		return USBD_IOERROR;
4134 
4135 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4136 	KASSERT(xfer->ux_length <= xfer->ux_bufsize);
4137 
4138 	len = xfer->ux_length;
4139 	endpt = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4140 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
4141 	sqh = epipe->sqh;
4142 
4143 	KASSERT(exfer->ex_isdone);
4144 #ifdef DIAGNOSTIC
4145 	exfer->ex_isdone = false;
4146 #endif
4147 
4148 	ehci_reset_sqtd_chain(sc, xfer, len, isread, &epipe->nexttoggle, &end);
4149 
4150 	end->qtd.qtd_status |= htole32(EHCI_QTD_IOC);
4151 	usb_syncmem(&end->dma, end->offs, sizeof(end->qtd),
4152 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4153 	exfer->ex_sqtdend = end;
4154 
4155 #ifdef EHCI_DEBUG
4156 	DPRINTFN(5, "--- dump start ---", 0, 0, 0, 0);
4157 	ehci_dump_sqh(sqh);
4158 	ehci_dump_sqtds(exfer->ex_sqtdstart);
4159 	DPRINTFN(5, "--- dump end ---", 0, 0, 0, 0);
4160 #endif
4161 
4162 	if (xfer->ux_length)
4163 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4164 		    isread ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
4165 
4166 	/* also does usb_syncmem(sqh) */
4167 	ehci_set_qh_qtd(sqh, exfer->ex_sqtdstart);
4168 	usbd_xfer_schedule_timeout(xfer);
4169 	ehci_add_intr_list(sc, exfer);
4170 	xfer->ux_status = USBD_IN_PROGRESS;
4171 
4172 #if 0
4173 #ifdef EHCI_DEBUG
4174 	DPRINTFN(5, "data(2)", 0, 0, 0, 0);
4175 //	delay(10000);
4176 	DPRINTFN(5, "data(3)", 0, 0, 0, 0);
4177 	ehci_dump_regs(sc);
4178 	DPRINTFN(5, "sqh:", 0, 0, 0, 0);
4179 	ehci_dump_sqh(sqh);
4180 	ehci_dump_sqtds(exfer->ex_sqtdstart);
4181 #endif
4182 #endif
4183 
4184 	return USBD_IN_PROGRESS;
4185 }
4186 
4187 Static void
4188 ehci_device_intr_abort(struct usbd_xfer *xfer)
4189 {
4190 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4191 
4192 	DPRINTF("xfer=%#jx", (uintptr_t)xfer, 0, 0, 0);
4193 
4194 	/*
4195 	 * XXX - abort_xfer uses ehci_sync_hc, which syncs via the advance
4196 	 *       async doorbell. That's dependent on the async list, wheras
4197 	 *       intr xfers are periodic, should not use this?
4198 	 */
4199 	usbd_xfer_abort(xfer);
4200 }
4201 
4202 Static void
4203 ehci_device_intr_close(struct usbd_pipe *pipe)
4204 {
4205 	ehci_softc_t *sc = EHCI_PIPE2SC(pipe);
4206 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(pipe);
4207 	struct ehci_soft_islot *isp;
4208 
4209 	KASSERT(mutex_owned(&sc->sc_lock));
4210 
4211 	isp = &sc->sc_islots[epipe->sqh->islot];
4212 	ehci_close_pipe(pipe, isp->sqh);
4213 }
4214 
4215 Static void
4216 ehci_device_intr_done(struct usbd_xfer *xfer)
4217 {
4218 	ehci_softc_t *sc __diagused = EHCI_XFER2SC(xfer);
4219 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4220 
4221 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4222 
4223 	DPRINTF("xfer=%#jx, actlen=%jd", (uintptr_t)xfer, xfer->ux_actlen, 0, 0);
4224 
4225 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
4226 
4227 	if (xfer->ux_length) {
4228 		int isread, endpt;
4229 
4230 		endpt = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4231 		isread = UE_GET_DIR(endpt) == UE_DIR_IN;
4232 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4233 		    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
4234 	}
4235 }
4236 
4237 /************************/
4238 Static int
4239 ehci_device_fs_isoc_init(struct usbd_xfer *xfer)
4240 {
4241 	struct ehci_pipe *epipe = EHCI_PIPE2EPIPE(xfer->ux_pipe);
4242 	struct usbd_device *dev = xfer->ux_pipe->up_dev;
4243 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4244 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4245 	ehci_soft_sitd_t *sitd, *prev, *start, *stop;
4246 	int i, k, frames;
4247 	u_int huba, dir;
4248 	int err;
4249 
4250 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4251 
4252 	start = NULL;
4253 	sitd = NULL;
4254 
4255 	DPRINTF("xfer %#jx len %jd flags %jd", (uintptr_t)xfer, xfer->ux_length,
4256 	    xfer->ux_flags, 0);
4257 
4258 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4259 	KASSERT(xfer->ux_nframes != 0);
4260 	KASSERT(exfer->ex_isdone);
4261 
4262 	exfer->ex_type = EX_FS_ISOC;
4263 	/*
4264 	 * Step 1: Allocate and initialize sitds.
4265 	 */
4266 	i = epipe->pipe.up_endpoint->ue_edesc->bInterval;
4267 	if (i > 16 || i == 0) {
4268 		/* Spec page 271 says intervals > 16 are invalid */
4269 		DPRINTF("bInterval %jd invalid", i, 0, 0, 0);
4270 		return EINVAL;
4271 	}
4272 
4273 	frames = xfer->ux_nframes;
4274 	for (i = 0, prev = NULL; i < frames; i++, prev = sitd) {
4275 		sitd = ehci_alloc_sitd(sc);
4276 		if (sitd == NULL) {
4277 			err = ENOMEM;
4278 			goto fail;
4279 		}
4280 
4281 		if (prev)
4282 			prev->xfer_next = sitd;
4283 		else
4284 			start = sitd;
4285 
4286 		huba = dev->ud_myhsport->up_parent->ud_addr;
4287 
4288 #if 0
4289 		if (sc->sc_flags & EHCIF_FREESCALE) {
4290 			// Set hub address to 0 if embedded TT is used.
4291 			if (huba == sc->sc_addr)
4292 				huba = 0;
4293 		}
4294 #endif
4295 
4296 		k = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4297 		dir = UE_GET_DIR(k) ? 1 : 0;
4298 		sitd->sitd.sitd_endp =
4299 		    htole32(EHCI_SITD_SET_ENDPT(UE_GET_ADDR(k)) |
4300 		    EHCI_SITD_SET_DADDR(dev->ud_addr) |
4301 		    EHCI_SITD_SET_PORT(dev->ud_myhsport->up_portno) |
4302 		    EHCI_SITD_SET_HUBA(huba) |
4303 		    EHCI_SITD_SET_DIR(dir));
4304 
4305 		sitd->sitd.sitd_back = htole32(EHCI_LINK_TERMINATE);
4306 	} /* End of frame */
4307 
4308 	sitd->sitd.sitd_trans |= htole32(EHCI_SITD_IOC);
4309 
4310 	stop = sitd;
4311 	stop->xfer_next = NULL;
4312 	exfer->ex_sitdstart = start;
4313 	exfer->ex_sitdend = stop;
4314 
4315 	return 0;
4316 
4317 fail:
4318 	mutex_enter(&sc->sc_lock);
4319 	ehci_soft_sitd_t *next;
4320 	for (sitd = start; sitd; sitd = next) {
4321 		next = sitd->xfer_next;
4322 		ehci_free_sitd_locked(sc, sitd);
4323 	}
4324 	mutex_exit(&sc->sc_lock);
4325 
4326 	return err;
4327 }
4328 
4329 Static void
4330 ehci_device_fs_isoc_fini(struct usbd_xfer *xfer)
4331 {
4332 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4333 	struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
4334 
4335 	KASSERT(ex->ex_type == EX_FS_ISOC);
4336 
4337 	ehci_free_sitd_chain(sc, ex->ex_sitdstart);
4338 }
4339 
4340 Static usbd_status
4341 ehci_device_fs_isoc_transfer(struct usbd_xfer *xfer)
4342 {
4343 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4344 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4345 	struct usbd_device *dev = xfer->ux_pipe->up_dev;
4346 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4347 	ehci_soft_sitd_t *sitd;
4348 	usb_dma_t *dma_buf;
4349 	int i, j, k, frames;
4350 	int offs;
4351 	int frindex;
4352 	u_int dir;
4353 
4354 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4355 
4356 	sitd = NULL;
4357 
4358 	DPRINTF("xfer %#jx len %jd flags %jd", (uintptr_t)xfer, xfer->ux_length,
4359 	    xfer->ux_flags, 0);
4360 
4361 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
4362 
4363 	if (sc->sc_dying)
4364 		return USBD_IOERROR;
4365 
4366 	/*
4367 	 * To avoid complication, don't allow a request right now that'll span
4368 	 * the entire frame table. To within 4 frames, to allow some leeway
4369 	 * on either side of where the hc currently is.
4370 	 */
4371 	if (epipe->pipe.up_endpoint->ue_edesc->bInterval *
4372 			xfer->ux_nframes >= sc->sc_flsize - 4) {
4373 		printf("ehci: isoc descriptor requested that spans the entire"
4374 		    " frametable, too many frames\n");
4375 		return USBD_INVAL;
4376 	}
4377 
4378 	KASSERT(xfer->ux_nframes != 0 && xfer->ux_frlengths);
4379 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4380 	KASSERT(exfer->ex_isdone);
4381 #ifdef DIAGNOSTIC
4382 	exfer->ex_isdone = false;
4383 #endif
4384 
4385 	/*
4386 	 * Step 1: Initialize sitds.
4387 	 */
4388 
4389 	frames = xfer->ux_nframes;
4390 	dma_buf = &xfer->ux_dmabuf;
4391 	offs = 0;
4392 
4393 	for (sitd = exfer->ex_sitdstart, i = 0; i < frames;
4394 	    i++, sitd = sitd->xfer_next) {
4395 		KASSERT(sitd != NULL);
4396 		KASSERT(xfer->ux_frlengths[i] <= 0x3ff);
4397 
4398 		sitd->sitd.sitd_trans = htole32(EHCI_SITD_ACTIVE |
4399 		    EHCI_SITD_SET_LEN(xfer->ux_frlengths[i]));
4400 
4401 		/* Set page0 index and offset - TP and T-offset are set below */
4402 		const bus_addr_t sba = DMAADDR(dma_buf, offs);
4403 		sitd->sitd.sitd_buffer[0] = htole32(BUS_ADDR_LO32(sba));
4404 		sitd->sitd.sitd_buffer_hi[0] = htole32(BUS_ADDR_HI32(sba));
4405 
4406 		offs += xfer->ux_frlengths[i];
4407 
4408 		const bus_addr_t eba = DMAADDR(dma_buf, offs - 1);
4409 		sitd->sitd.sitd_buffer[1] =
4410 		    htole32(EHCI_SITD_SET_BPTR(BUS_ADDR_LO32(eba)));
4411 		sitd->sitd.sitd_buffer_hi[1] = htole32(BUS_ADDR_HI32(eba));
4412 
4413 		u_int huba __diagused = dev->ud_myhsport->up_parent->ud_addr;
4414 
4415 #if 0
4416 		if (sc->sc_flags & EHCIF_FREESCALE) {
4417 			// Set hub address to 0 if embedded TT is used.
4418 			if (huba == sc->sc_addr)
4419 				huba = 0;
4420 		}
4421 #endif
4422 
4423 		k = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4424 		dir = UE_GET_DIR(k) ? 1 : 0;
4425 		KASSERT(sitd->sitd.sitd_endp == htole32(
4426 		    EHCI_SITD_SET_ENDPT(UE_GET_ADDR(k)) |
4427 		    EHCI_SITD_SET_DADDR(dev->ud_addr) |
4428 		    EHCI_SITD_SET_PORT(dev->ud_myhsport->up_portno) |
4429 		    EHCI_SITD_SET_HUBA(huba) |
4430 		    EHCI_SITD_SET_DIR(dir)));
4431 		KASSERT(sitd->sitd.sitd_back == htole32(EHCI_LINK_TERMINATE));
4432 
4433 		uint8_t sa = 0;
4434 		uint8_t sb = 0;
4435 		u_int temp, tlen;
4436 
4437 		if (dir == 0) {	/* OUT */
4438 			temp = 0;
4439 			tlen = xfer->ux_frlengths[i];
4440 			if (tlen <= 188) {
4441 				temp |= 1;	/* T-count = 1, TP = ALL */
4442 				tlen = 1;
4443 			} else {
4444 				tlen += 187;
4445 				tlen /= 188;
4446 				temp |= tlen;	/* T-count = [1..6] */
4447 				temp |= 8;	/* TP = Begin */
4448 			}
4449 			sitd->sitd.sitd_buffer[1] |= htole32(temp);
4450 
4451 			tlen += sa;
4452 
4453 			if (tlen >= 8) {
4454 				sb = 0;
4455 			} else {
4456 				sb = (1 << tlen);
4457 			}
4458 
4459 			sa = (1 << sa);
4460 			sa = (sb - sa) & 0x3F;
4461 			sb = 0;
4462 		} else {
4463 			sb = (-(4 << sa)) & 0xFE;
4464 			sa = (1 << sa) & 0x3F;
4465 			sa = 0x01;
4466 			sb = 0xfc;
4467 		}
4468 
4469 		sitd->sitd.sitd_sched = htole32(
4470 		    EHCI_SITD_SET_SMASK(sa) |
4471 		    EHCI_SITD_SET_CMASK(sb)
4472 		    );
4473 
4474 		usb_syncmem(&sitd->dma, sitd->offs, sizeof(ehci_sitd_t),
4475 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4476 	} /* End of frame */
4477 
4478 	sitd = exfer->ex_sitdend;
4479 	sitd->sitd.sitd_trans |= htole32(EHCI_SITD_IOC);
4480 
4481 	usb_syncmem(&sitd->dma, sitd->offs + offsetof(ehci_sitd_t, sitd_trans),
4482 	    sizeof(sitd->sitd.sitd_trans),
4483 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4484 
4485 	if (xfer->ux_length)
4486 		usb_syncmem(&exfer->ex_xfer.ux_dmabuf, 0, xfer->ux_length,
4487 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
4488 
4489 	/*
4490 	 * Part 2: Transfer descriptors have now been set up, now they must
4491 	 * be scheduled into the periodic frame list. Erk. Not wanting to
4492 	 * complicate matters, transfer is denied if the transfer spans
4493 	 * more than the periodic frame list.
4494 	 */
4495 
4496 	/* Start inserting frames */
4497 	if (epipe->isoc.cur_xfers > 0) {
4498 		frindex = epipe->isoc.next_frame;
4499 	} else {
4500 		frindex = EOREAD4(sc, EHCI_FRINDEX);
4501 		frindex = frindex >> 3; /* Erase microframe index */
4502 		frindex += 2;
4503 	}
4504 
4505 	if (frindex >= sc->sc_flsize)
4506 		frindex &= (sc->sc_flsize - 1);
4507 
4508 	/* What's the frame interval? */
4509 	i = epipe->pipe.up_endpoint->ue_edesc->bInterval;
4510 
4511 	for (sitd = exfer->ex_sitdstart, j = 0; j < frames;
4512 	    j++, sitd = sitd->xfer_next) {
4513 		KASSERT(sitd);
4514 
4515 		usb_syncmem(&sc->sc_fldma,
4516 		    sizeof(ehci_link_t) * frindex,
4517 		    sizeof(ehci_link_t),
4518 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
4519 
4520 		sitd->sitd.sitd_next = sc->sc_flist[frindex];
4521 		if (sitd->sitd.sitd_next == 0)
4522 			/*
4523 			 * FIXME: frindex table gets initialized to NULL
4524 			 * or EHCI_NULL?
4525 			 */
4526 			sitd->sitd.sitd_next = EHCI_NULL;
4527 
4528 		usb_syncmem(&sitd->dma,
4529 		    sitd->offs + offsetof(ehci_sitd_t, sitd_next),
4530 		    sizeof(ehci_sitd_t),
4531 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4532 
4533 		sc->sc_flist[frindex] =
4534 		    htole32(EHCI_LINK_SITD | sitd->physaddr);
4535 
4536 		usb_syncmem(&sc->sc_fldma,
4537 		    sizeof(ehci_link_t) * frindex,
4538 		    sizeof(ehci_link_t),
4539 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4540 
4541 		sitd->frame_list.next = sc->sc_softsitds[frindex];
4542 		sc->sc_softsitds[frindex] = sitd;
4543 		if (sitd->frame_list.next != NULL)
4544 			sitd->frame_list.next->frame_list.prev = sitd;
4545 		sitd->slot = frindex;
4546 		sitd->frame_list.prev = NULL;
4547 
4548 		frindex += i;
4549 		if (frindex >= sc->sc_flsize)
4550 			frindex -= sc->sc_flsize;
4551 	}
4552 
4553 	epipe->isoc.cur_xfers++;
4554 	epipe->isoc.next_frame = frindex;
4555 
4556 	ehci_add_intr_list(sc, exfer);
4557 	xfer->ux_status = USBD_IN_PROGRESS;
4558 
4559 	return USBD_IN_PROGRESS;
4560 }
4561 
4562 Static void
4563 ehci_device_fs_isoc_abort(struct usbd_xfer *xfer)
4564 {
4565 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4566 
4567 	DPRINTF("xfer = %#jx", (uintptr_t)xfer, 0, 0, 0);
4568 	ehci_abort_isoc_xfer(xfer, USBD_CANCELLED);
4569 }
4570 
4571 Static void
4572 ehci_device_fs_isoc_close(struct usbd_pipe *pipe)
4573 {
4574 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4575 
4576 	DPRINTF("nothing in the pipe to free?", 0, 0, 0, 0);
4577 }
4578 
4579 Static void
4580 ehci_device_fs_isoc_done(struct usbd_xfer *xfer)
4581 {
4582 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4583 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4584 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4585 
4586 	KASSERT(mutex_owned(&sc->sc_lock));
4587 
4588 	epipe->isoc.cur_xfers--;
4589 	ehci_remove_sitd_chain(sc, exfer->ex_itdstart);
4590 
4591 	if (xfer->ux_length)
4592 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4593 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
4594 }
4595 
4596 /* -------------------------------------------------------------------------- */
4597 
4598 Static int
4599 ehci_device_isoc_init(struct usbd_xfer *xfer)
4600 {
4601 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4602 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4603 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4604 	ehci_soft_itd_t *itd, *prev, *start, *stop;
4605 	int i, j, k;
4606 	int frames, ufrperframe;
4607 	int err;
4608 
4609 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4610 
4611 	start = NULL;
4612 	prev = NULL;
4613 	itd = NULL;
4614 
4615 	KASSERT(xfer->ux_nframes != 0);
4616 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4617 	KASSERT(exfer->ex_isdone);
4618 
4619 	exfer->ex_type = EX_ISOC;
4620 
4621 	/*
4622 	 * Step 1: Allocate and initialize itds, how many do we need?
4623 	 * One per transfer if interval >= 8 microframes, less if we use
4624 	 * multiple microframes per frame.
4625 	 */
4626 	i = epipe->pipe.up_endpoint->ue_edesc->bInterval;
4627 	if (i > 16 || i == 0) {
4628 		/* Spec page 271 says intervals > 16 are invalid */
4629 		DPRINTF("bInterval %jd invalid", i, 0, 0, 0);
4630 		return EINVAL;
4631 	}
4632 
4633 	ufrperframe = uimax(1, USB_UFRAMES_PER_FRAME / (1 << (i - 1)));
4634 	frames = howmany(xfer->ux_nframes, ufrperframe);
4635 
4636 	for (i = 0, prev = NULL; i < frames; i++, prev = itd) {
4637 		itd = ehci_alloc_itd(sc);
4638 		if (itd == NULL) {
4639 			err = ENOMEM;
4640 			goto fail;
4641 		}
4642 
4643 		if (prev != NULL) {
4644 			/* Maybe not as it's updated by the scheduling? */
4645 			prev->itd.itd_next =
4646 			    htole32(itd->physaddr | EHCI_LINK_ITD);
4647 
4648 			prev->xfer_next = itd;
4649 		} else {
4650 			start = itd;
4651 		}
4652 
4653 		/*
4654 		 * Other special values
4655 		 */
4656 		k = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4657 		itd->itd.itd_bufr[0] = htole32(
4658 		    EHCI_ITD_SET_EP(UE_GET_ADDR(k)) |
4659 		    EHCI_ITD_SET_DADDR(epipe->pipe.up_dev->ud_addr));
4660 
4661 		k = (UE_GET_DIR(epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress))
4662 		    ? 1 : 0;
4663 		j = UGETW(epipe->pipe.up_endpoint->ue_edesc->wMaxPacketSize);
4664 		itd->itd.itd_bufr[1] |= htole32(
4665 		    EHCI_ITD_SET_DIR(k) |
4666 		    EHCI_ITD_SET_MAXPKT(UE_GET_SIZE(j)));
4667 
4668 		/* FIXME: handle invalid trans - should be done in openpipe */
4669 		itd->itd.itd_bufr[2] |=
4670 		    htole32(EHCI_ITD_SET_MULTI(UE_GET_TRANS(j)+1));
4671 	} /* End of frame */
4672 
4673 	stop = itd;
4674 	stop->xfer_next = NULL;
4675 
4676 	exfer->ex_itdstart = start;
4677 	exfer->ex_itdend = stop;
4678 
4679 	return 0;
4680 fail:
4681 	mutex_enter(&sc->sc_lock);
4682 	ehci_soft_itd_t *next;
4683 	for (itd = start; itd; itd = next) {
4684 		next = itd->xfer_next;
4685 		ehci_free_itd_locked(sc, itd);
4686 	}
4687 	mutex_exit(&sc->sc_lock);
4688 
4689 	return err;
4690 
4691 }
4692 
4693 Static void
4694 ehci_device_isoc_fini(struct usbd_xfer *xfer)
4695 {
4696 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4697 	struct ehci_xfer *ex = EHCI_XFER2EXFER(xfer);
4698 
4699 	KASSERT(ex->ex_type == EX_ISOC);
4700 
4701 	ehci_free_itd_chain(sc, ex->ex_itdstart);
4702 }
4703 
4704 Static usbd_status
4705 ehci_device_isoc_transfer(struct usbd_xfer *xfer)
4706 {
4707 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4708 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4709 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4710 	ehci_soft_itd_t *itd, *prev;
4711 	usb_dma_t *dma_buf;
4712 	int i, j;
4713 	int frames, uframes, ufrperframe;
4714 	int trans_count, offs;
4715 	int frindex;
4716 
4717 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4718 
4719 	prev = NULL;
4720 	itd = NULL;
4721 	trans_count = 0;
4722 
4723 	DPRINTF("xfer %#jx flags %jd", (uintptr_t)xfer, xfer->ux_flags, 0, 0);
4724 
4725 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
4726 
4727 	if (sc->sc_dying)
4728 		return USBD_IOERROR;
4729 
4730 	/*
4731 	 * To avoid complication, don't allow a request right now that'll span
4732 	 * the entire frame table. To within 4 frames, to allow some leeway
4733 	 * on either side of where the hc currently is.
4734 	 */
4735 	if ((1 << (epipe->pipe.up_endpoint->ue_edesc->bInterval)) *
4736 			xfer->ux_nframes >= (sc->sc_flsize - 4) * 8) {
4737 		DPRINTF(
4738 		    "isoc descriptor spans entire frametable", 0, 0, 0, 0);
4739 		printf("ehci: isoc descriptor requested that spans the entire frametable, too many frames\n");
4740 		return USBD_INVAL;
4741 	}
4742 
4743 	KASSERT(xfer->ux_nframes != 0 && xfer->ux_frlengths);
4744 	KASSERT(!(xfer->ux_rqflags & URQ_REQUEST));
4745 	KASSERT(exfer->ex_isdone);
4746 #ifdef DIAGNOSTIC
4747 	exfer->ex_isdone = false;
4748 #endif
4749 
4750 	/*
4751 	 * Step 1: Re-Initialize itds
4752 	 */
4753 
4754 	i = epipe->pipe.up_endpoint->ue_edesc->bInterval;
4755 	if (i > 16 || i == 0) {
4756 		/* Spec page 271 says intervals > 16 are invalid */
4757 		DPRINTF("bInterval %jd invalid", i, 0, 0, 0);
4758 		return USBD_INVAL;
4759 	}
4760 
4761 	ufrperframe = uimax(1, USB_UFRAMES_PER_FRAME / (1 << (i - 1)));
4762 	frames = howmany(xfer->ux_nframes, ufrperframe);
4763 	uframes = USB_UFRAMES_PER_FRAME / ufrperframe;
4764 
4765 	if (frames == 0) {
4766 		DPRINTF("frames == 0", 0, 0, 0, 0);
4767 		return USBD_INVAL;
4768 	}
4769 
4770 	dma_buf = &xfer->ux_dmabuf;
4771 	offs = 0;
4772 
4773 	itd = exfer->ex_itdstart;
4774 	for (i = 0; i < frames; i++, itd = itd->xfer_next) {
4775 		int froffs = offs;
4776 
4777 		if (prev != NULL) {
4778 			prev->itd.itd_next =
4779 			    htole32(itd->physaddr | EHCI_LINK_ITD);
4780 			usb_syncmem(&prev->dma,
4781 			    prev->offs + offsetof(ehci_itd_t, itd_next),
4782 			    sizeof(prev->itd.itd_next), BUS_DMASYNC_POSTWRITE);
4783 			prev->xfer_next = itd;
4784 		}
4785 
4786 		/*
4787 		 * Step 1.5, initialize uframes
4788 		 */
4789 		for (j = 0; j < EHCI_ITD_NUFRAMES; j += uframes) {
4790 			/* Calculate which page in the list this starts in */
4791 			int addr = DMAADDR(dma_buf, froffs);
4792 			addr = EHCI_PAGE_OFFSET(addr);
4793 			addr += (offs - froffs);
4794 			addr = EHCI_PAGE(addr);
4795 			addr /= EHCI_PAGE_SIZE;
4796 
4797 			/*
4798 			 * This gets the initial offset into the first page,
4799 			 * looks how far further along the current uframe
4800 			 * offset is. Works out how many pages that is.
4801 			 */
4802 
4803 			itd->itd.itd_ctl[j] = htole32 ( EHCI_ITD_ACTIVE |
4804 			    EHCI_ITD_SET_LEN(xfer->ux_frlengths[trans_count]) |
4805 			    EHCI_ITD_SET_PG(addr) |
4806 			    EHCI_ITD_SET_OFFS(EHCI_PAGE_OFFSET(DMAADDR(dma_buf,offs))));
4807 
4808 			offs += xfer->ux_frlengths[trans_count];
4809 			trans_count++;
4810 
4811 			if (trans_count >= xfer->ux_nframes) { /*Set IOC*/
4812 				itd->itd.itd_ctl[j] |= htole32(EHCI_ITD_IOC);
4813 				break;
4814 			}
4815 		}
4816 
4817 		/*
4818 		 * Step 1.75, set buffer pointers. To simplify matters, all
4819 		 * pointers are filled out for the next 7 hardware pages in
4820 		 * the dma block, so no need to worry what pages to cover
4821 		 * and what to not.
4822 		 */
4823 
4824 		for (j = 0; j < EHCI_ITD_NBUFFERS; j++) {
4825 			/*
4826 			 * Don't try to lookup a page that's past the end
4827 			 * of buffer
4828 			 */
4829 			int page_offs = EHCI_PAGE(froffs + (EHCI_PAGE_SIZE * j));
4830 			if (page_offs >= dma_buf->udma_block->size)
4831 				break;
4832 
4833 			uint64_t page = DMAADDR(dma_buf, page_offs);
4834 			page = EHCI_PAGE(page);
4835 			itd->itd.itd_bufr[j] = htole32(EHCI_ITD_SET_BPTR(page));
4836 			itd->itd.itd_bufr_hi[j] = htole32(page >> 32);
4837 		}
4838 		/*
4839 		 * Other special values
4840 		 */
4841 
4842 		int k = epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress;
4843 		itd->itd.itd_bufr[0] |= htole32(EHCI_ITD_SET_EP(UE_GET_ADDR(k)) |
4844 		    EHCI_ITD_SET_DADDR(epipe->pipe.up_dev->ud_addr));
4845 
4846 		k = (UE_GET_DIR(epipe->pipe.up_endpoint->ue_edesc->bEndpointAddress))
4847 		    ? 1 : 0;
4848 		j = UGETW(epipe->pipe.up_endpoint->ue_edesc->wMaxPacketSize);
4849 		itd->itd.itd_bufr[1] |= htole32(EHCI_ITD_SET_DIR(k) |
4850 		    EHCI_ITD_SET_MAXPKT(UE_GET_SIZE(j)));
4851 
4852 		/* FIXME: handle invalid trans */
4853 		itd->itd.itd_bufr[2] |=
4854 		    htole32(EHCI_ITD_SET_MULTI(UE_GET_TRANS(j)+1));
4855 
4856 		usb_syncmem(&itd->dma, itd->offs, sizeof(ehci_itd_t),
4857 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4858 
4859 		prev = itd;
4860 	} /* End of frame */
4861 
4862 	if (xfer->ux_length)
4863 		usb_syncmem(&exfer->ex_xfer.ux_dmabuf, 0, xfer->ux_length,
4864 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
4865 
4866 	/*
4867 	 * Part 2: Transfer descriptors have now been set up, now they must
4868 	 * be scheduled into the periodic frame list. Erk. Not wanting to
4869 	 * complicate matters, transfer is denied if the transfer spans
4870 	 * more than the periodic frame list.
4871 	 */
4872 
4873 	/* Start inserting frames */
4874 	if (epipe->isoc.cur_xfers > 0) {
4875 		frindex = epipe->isoc.next_frame;
4876 	} else {
4877 		frindex = EOREAD4(sc, EHCI_FRINDEX);
4878 		frindex = frindex >> 3; /* Erase microframe index */
4879 		frindex += 2;
4880 	}
4881 
4882 	if (frindex >= sc->sc_flsize)
4883 		frindex &= (sc->sc_flsize - 1);
4884 
4885 	/* What's the frame interval? */
4886 	i = (1 << (epipe->pipe.up_endpoint->ue_edesc->bInterval - 1));
4887 	if (i / USB_UFRAMES_PER_FRAME == 0)
4888 		i = 1;
4889 	else
4890 		i /= USB_UFRAMES_PER_FRAME;
4891 
4892 	itd = exfer->ex_itdstart;
4893 	for (j = 0; j < frames; j++) {
4894 		KASSERTMSG(itd != NULL, "frame %d\n", j);
4895 
4896 		usb_syncmem(&sc->sc_fldma,
4897 		    sizeof(ehci_link_t) * frindex,
4898 		    sizeof(ehci_link_t),
4899 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
4900 
4901 		itd->itd.itd_next = sc->sc_flist[frindex];
4902 		if (itd->itd.itd_next == 0)
4903 			/*
4904 			 * FIXME: frindex table gets initialized to NULL
4905 			 * or EHCI_NULL?
4906 			 */
4907 			itd->itd.itd_next = EHCI_NULL;
4908 
4909 		usb_syncmem(&itd->dma,
4910 		    itd->offs + offsetof(ehci_itd_t, itd_next),
4911 		    sizeof(itd->itd.itd_next),
4912 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4913 
4914 		sc->sc_flist[frindex] = htole32(EHCI_LINK_ITD | itd->physaddr);
4915 
4916 		usb_syncmem(&sc->sc_fldma,
4917 		    sizeof(ehci_link_t) * frindex,
4918 		    sizeof(ehci_link_t),
4919 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
4920 
4921 		itd->frame_list.next = sc->sc_softitds[frindex];
4922 		sc->sc_softitds[frindex] = itd;
4923 		if (itd->frame_list.next != NULL)
4924 			itd->frame_list.next->frame_list.prev = itd;
4925 		itd->slot = frindex;
4926 		itd->frame_list.prev = NULL;
4927 
4928 		frindex += i;
4929 		if (frindex >= sc->sc_flsize)
4930 			frindex -= sc->sc_flsize;
4931 
4932 		itd = itd->xfer_next;
4933 	}
4934 
4935 	epipe->isoc.cur_xfers++;
4936 	epipe->isoc.next_frame = frindex;
4937 
4938 	ehci_add_intr_list(sc, exfer);
4939 	xfer->ux_status = USBD_IN_PROGRESS;
4940 
4941 	return USBD_IN_PROGRESS;
4942 }
4943 
4944 Static void
4945 ehci_device_isoc_abort(struct usbd_xfer *xfer)
4946 {
4947 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4948 
4949 	DPRINTF("xfer = %#jx", (uintptr_t)xfer, 0, 0, 0);
4950 	ehci_abort_isoc_xfer(xfer, USBD_CANCELLED);
4951 }
4952 
4953 Static void
4954 ehci_device_isoc_close(struct usbd_pipe *pipe)
4955 {
4956 	EHCIHIST_FUNC(); EHCIHIST_CALLED();
4957 
4958 	DPRINTF("nothing in the pipe to free?", 0, 0, 0, 0);
4959 }
4960 
4961 Static void
4962 ehci_device_isoc_done(struct usbd_xfer *xfer)
4963 {
4964 	struct ehci_xfer *exfer = EHCI_XFER2EXFER(xfer);
4965 	ehci_softc_t *sc = EHCI_XFER2SC(xfer);
4966 	struct ehci_pipe *epipe = EHCI_XFER2EPIPE(xfer);
4967 
4968 	KASSERT(mutex_owned(&sc->sc_lock));
4969 
4970 	epipe->isoc.cur_xfers--;
4971 	ehci_remove_itd_chain(sc, exfer->ex_sitdstart);
4972 	if (xfer->ux_length)
4973 		usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4974 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
4975 }
4976