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