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