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