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