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