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