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