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