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