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