]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/dev/usb/controller/xhci.c
MFC r279233:
[FreeBSD/stable/9.git] / sys / dev / usb / controller / xhci.c
1 /*-
2  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25
26 /*
27  * USB eXtensible Host Controller Interface, a.k.a. USB 3.0 controller.
28  *
29  * The XHCI 1.0 spec can be found at
30  * http://www.intel.com/technology/usb/download/xHCI_Specification_for_USB.pdf
31  * and the USB 3.0 spec at
32  * http://www.usb.org/developers/docs/usb_30_spec_060910.zip
33  */
34
35 /*
36  * A few words about the design implementation: This driver emulates
37  * the concept about TDs which is found in EHCI specification. This
38  * way we avoid too much diveration among USB drivers.
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include <sys/stdint.h>
45 #include <sys/stddef.h>
46 #include <sys/param.h>
47 #include <sys/queue.h>
48 #include <sys/types.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
51 #include <sys/bus.h>
52 #include <sys/module.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/condvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sx.h>
58 #include <sys/unistd.h>
59 #include <sys/callout.h>
60 #include <sys/malloc.h>
61 #include <sys/priv.h>
62
63 #include <dev/usb/usb.h>
64 #include <dev/usb/usbdi.h>
65
66 #define USB_DEBUG_VAR xhcidebug
67
68 #include <dev/usb/usb_core.h>
69 #include <dev/usb/usb_debug.h>
70 #include <dev/usb/usb_busdma.h>
71 #include <dev/usb/usb_process.h>
72 #include <dev/usb/usb_transfer.h>
73 #include <dev/usb/usb_device.h>
74 #include <dev/usb/usb_hub.h>
75 #include <dev/usb/usb_util.h>
76
77 #include <dev/usb/usb_controller.h>
78 #include <dev/usb/usb_bus.h>
79 #include <dev/usb/controller/xhci.h>
80 #include <dev/usb/controller/xhcireg.h>
81
82 #define XHCI_BUS2SC(bus) \
83    ((struct xhci_softc *)(((uint8_t *)(bus)) - \
84     ((uint8_t *)&(((struct xhci_softc *)0)->sc_bus))))
85
86 #ifdef USB_DEBUG
87 static int xhcidebug;
88 static int xhciroute;
89 static int xhcipolling;
90
91 static SYSCTL_NODE(_hw_usb, OID_AUTO, xhci, CTLFLAG_RW, 0, "USB XHCI");
92 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_TUN,
93     &xhcidebug, 0, "Debug level");
94 TUNABLE_INT("hw.usb.xhci.debug", &xhcidebug);
95 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, xhci_port_route, CTLFLAG_RW | CTLFLAG_TUN,
96     &xhciroute, 0, "Routing bitmap for switching EHCI ports to XHCI controller");
97 TUNABLE_INT("hw.usb.xhci.xhci_port_route", &xhciroute);
98 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, use_polling, CTLFLAG_RW | CTLFLAG_TUN,
99     &xhcipolling, 0, "Set to enable software interrupt polling for XHCI controller");
100 TUNABLE_INT("hw.usb.xhci.use_polling", &xhcipolling);
101 #else
102 #define xhciroute 0
103 #endif
104
105 #define XHCI_INTR_ENDPT 1
106
107 struct xhci_std_temp {
108         struct xhci_softc       *sc;
109         struct usb_page_cache   *pc;
110         struct xhci_td          *td;
111         struct xhci_td          *td_next;
112         uint32_t                len;
113         uint32_t                offset;
114         uint32_t                max_packet_size;
115         uint32_t                average;
116         uint16_t                isoc_delta;
117         uint16_t                isoc_frame;
118         uint8_t                 shortpkt;
119         uint8_t                 multishort;
120         uint8_t                 last_frame;
121         uint8_t                 trb_type;
122         uint8_t                 direction;
123         uint8_t                 tbc;
124         uint8_t                 tlbpc;
125         uint8_t                 step_td;
126         uint8_t                 do_isoc_sync;
127 };
128
129 static void     xhci_do_poll(struct usb_bus *);
130 static void     xhci_device_done(struct usb_xfer *, usb_error_t);
131 static void     xhci_root_intr(struct xhci_softc *);
132 static void     xhci_free_device_ext(struct usb_device *);
133 static struct xhci_endpoint_ext *xhci_get_endpoint_ext(struct usb_device *,
134                     struct usb_endpoint_descriptor *);
135 static usb_proc_callback_t xhci_configure_msg;
136 static usb_error_t xhci_configure_device(struct usb_device *);
137 static usb_error_t xhci_configure_endpoint(struct usb_device *,
138                     struct usb_endpoint_descriptor *, uint64_t, uint16_t,
139                     uint8_t, uint8_t, uint8_t, uint16_t, uint16_t);
140 static usb_error_t xhci_configure_mask(struct usb_device *,
141                     uint32_t, uint8_t);
142 static usb_error_t xhci_cmd_evaluate_ctx(struct xhci_softc *,
143                     uint64_t, uint8_t);
144 static void xhci_endpoint_doorbell(struct usb_xfer *);
145 static void xhci_ctx_set_le32(struct xhci_softc *sc, volatile uint32_t *ptr, uint32_t val);
146 static uint32_t xhci_ctx_get_le32(struct xhci_softc *sc, volatile uint32_t *ptr);
147 static void xhci_ctx_set_le64(struct xhci_softc *sc, volatile uint64_t *ptr, uint64_t val);
148 #ifdef USB_DEBUG
149 static uint64_t xhci_ctx_get_le64(struct xhci_softc *sc, volatile uint64_t *ptr);
150 #endif
151
152 extern struct usb_bus_methods xhci_bus_methods;
153
154 #ifdef USB_DEBUG
155 static void
156 xhci_dump_trb(struct xhci_trb *trb)
157 {
158         DPRINTFN(5, "trb = %p\n", trb);
159         DPRINTFN(5, "qwTrb0 = 0x%016llx\n", (long long)le64toh(trb->qwTrb0));
160         DPRINTFN(5, "dwTrb2 = 0x%08x\n", le32toh(trb->dwTrb2));
161         DPRINTFN(5, "dwTrb3 = 0x%08x\n", le32toh(trb->dwTrb3));
162 }
163
164 static void
165 xhci_dump_endpoint(struct xhci_softc *sc, struct xhci_endp_ctx *pep)
166 {
167         DPRINTFN(5, "pep = %p\n", pep);
168         DPRINTFN(5, "dwEpCtx0=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx0));
169         DPRINTFN(5, "dwEpCtx1=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx1));
170         DPRINTFN(5, "qwEpCtx2=0x%016llx\n", (long long)xhci_ctx_get_le64(sc, &pep->qwEpCtx2));
171         DPRINTFN(5, "dwEpCtx4=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx4));
172         DPRINTFN(5, "dwEpCtx5=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx5));
173         DPRINTFN(5, "dwEpCtx6=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx6));
174         DPRINTFN(5, "dwEpCtx7=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx7));
175 }
176
177 static void
178 xhci_dump_device(struct xhci_softc *sc, struct xhci_slot_ctx *psl)
179 {
180         DPRINTFN(5, "psl = %p\n", psl);
181         DPRINTFN(5, "dwSctx0=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx0));
182         DPRINTFN(5, "dwSctx1=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx1));
183         DPRINTFN(5, "dwSctx2=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx2));
184         DPRINTFN(5, "dwSctx3=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx3));
185 }
186 #endif
187
188 uint8_t
189 xhci_use_polling(void)
190 {
191 #ifdef USB_DEBUG
192         return (xhcipolling != 0);
193 #else
194         return (0);
195 #endif
196 }
197
198 static void
199 xhci_iterate_hw_softc(struct usb_bus *bus, usb_bus_mem_sub_cb_t *cb)
200 {
201         struct xhci_softc *sc = XHCI_BUS2SC(bus);
202         uint8_t i;
203
204         cb(bus, &sc->sc_hw.root_pc, &sc->sc_hw.root_pg,
205            sizeof(struct xhci_hw_root), XHCI_PAGE_SIZE);
206
207         cb(bus, &sc->sc_hw.ctx_pc, &sc->sc_hw.ctx_pg,
208            sizeof(struct xhci_dev_ctx_addr), XHCI_PAGE_SIZE);
209
210         for (i = 0; i != XHCI_MAX_SCRATCHPADS; i++) {
211                 cb(bus, &sc->sc_hw.scratch_pc[i], &sc->sc_hw.scratch_pg[i],
212                     XHCI_PAGE_SIZE, XHCI_PAGE_SIZE);
213         }
214 }
215
216 static void
217 xhci_ctx_set_le32(struct xhci_softc *sc, volatile uint32_t *ptr, uint32_t val)
218 {
219         if (sc->sc_ctx_is_64_byte) {
220                 uint32_t offset;
221                 /* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
222                 /* all contexts are initially 32-bytes */
223                 offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
224                 ptr = (volatile uint32_t *)(((volatile uint8_t *)ptr) + offset);
225         }
226         *ptr = htole32(val);
227 }
228
229 static uint32_t
230 xhci_ctx_get_le32(struct xhci_softc *sc, volatile uint32_t *ptr)
231 {
232         if (sc->sc_ctx_is_64_byte) {
233                 uint32_t offset;
234                 /* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
235                 /* all contexts are initially 32-bytes */
236                 offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
237                 ptr = (volatile uint32_t *)(((volatile uint8_t *)ptr) + offset);
238         }
239         return (le32toh(*ptr));
240 }
241
242 static void
243 xhci_ctx_set_le64(struct xhci_softc *sc, volatile uint64_t *ptr, uint64_t val)
244 {
245         if (sc->sc_ctx_is_64_byte) {
246                 uint32_t offset;
247                 /* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
248                 /* all contexts are initially 32-bytes */
249                 offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
250                 ptr = (volatile uint64_t *)(((volatile uint8_t *)ptr) + offset);
251         }
252         *ptr = htole64(val);
253 }
254
255 #ifdef USB_DEBUG
256 static uint64_t
257 xhci_ctx_get_le64(struct xhci_softc *sc, volatile uint64_t *ptr)
258 {
259         if (sc->sc_ctx_is_64_byte) {
260                 uint32_t offset;
261                 /* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
262                 /* all contexts are initially 32-bytes */
263                 offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
264                 ptr = (volatile uint64_t *)(((volatile uint8_t *)ptr) + offset);
265         }
266         return (le64toh(*ptr));
267 }
268 #endif
269
270 static int
271 xhci_reset_command_queue_locked(struct xhci_softc *sc)
272 {
273         struct usb_page_search buf_res;
274         struct xhci_hw_root *phwr;
275         uint64_t addr;
276         uint32_t temp;
277
278         DPRINTF("\n");
279
280         temp = XREAD4(sc, oper, XHCI_CRCR_LO);
281         if (temp & XHCI_CRCR_LO_CRR) {
282                 DPRINTF("Command ring running\n");
283                 temp &= ~(XHCI_CRCR_LO_CS | XHCI_CRCR_LO_CA);
284
285                 /*
286                  * Try to abort the last command as per section
287                  * 4.6.1.2 "Aborting a Command" of the XHCI
288                  * specification:
289                  */
290
291                 /* stop and cancel */
292                 XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CS);
293                 XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
294
295                 XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CA);
296                 XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
297
298                 /* wait 250ms */
299                 usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 4);
300
301                 /* check if command ring is still running */
302                 temp = XREAD4(sc, oper, XHCI_CRCR_LO);
303                 if (temp & XHCI_CRCR_LO_CRR) {
304                         DPRINTF("Comand ring still running\n");
305                         return (USB_ERR_IOERROR);
306                 }
307         }
308
309         /* reset command ring */
310         sc->sc_command_ccs = 1;
311         sc->sc_command_idx = 0;
312
313         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
314
315         /* set up command ring control base address */
316         addr = buf_res.physaddr;
317         phwr = buf_res.buffer;
318         addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[0];
319
320         DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
321
322         memset(phwr->hwr_commands, 0, sizeof(phwr->hwr_commands));
323         phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
324
325         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
326
327         XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
328         XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
329
330         return (0);
331 }
332
333 usb_error_t
334 xhci_start_controller(struct xhci_softc *sc)
335 {
336         struct usb_page_search buf_res;
337         struct xhci_hw_root *phwr;
338         struct xhci_dev_ctx_addr *pdctxa;
339         uint64_t addr;
340         uint32_t temp;
341         uint16_t i;
342
343         DPRINTF("\n");
344
345         sc->sc_event_ccs = 1;
346         sc->sc_event_idx = 0;
347         sc->sc_command_ccs = 1;
348         sc->sc_command_idx = 0;
349
350         /* Reset controller */
351         XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_HCRST);
352
353         for (i = 0; i != 100; i++) {
354                 usb_pause_mtx(NULL, hz / 100);
355                 temp = (XREAD4(sc, oper, XHCI_USBCMD) & XHCI_CMD_HCRST) |
356                     (XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_CNR);
357                 if (!temp)
358                         break;
359         }
360
361         if (temp) {
362                 device_printf(sc->sc_bus.parent, "Controller "
363                     "reset timeout.\n");
364                 return (USB_ERR_IOERROR);
365         }
366
367         if (!(XREAD4(sc, oper, XHCI_PAGESIZE) & XHCI_PAGESIZE_4K)) {
368                 device_printf(sc->sc_bus.parent, "Controller does "
369                     "not support 4K page size.\n");
370                 return (USB_ERR_IOERROR);
371         }
372
373         temp = XREAD4(sc, capa, XHCI_HCSPARAMS1);
374
375         i = XHCI_HCS1_N_PORTS(temp);
376
377         if (i == 0) {
378                 device_printf(sc->sc_bus.parent, "Invalid number "
379                     "of ports: %u\n", i);
380                 return (USB_ERR_IOERROR);
381         }
382
383         sc->sc_noport = i;
384         sc->sc_noslot = XHCI_HCS1_DEVSLOT_MAX(temp);
385
386         if (sc->sc_noslot > XHCI_MAX_DEVICES)
387                 sc->sc_noslot = XHCI_MAX_DEVICES;
388
389         /* set up number of device slots */
390
391         DPRINTF("CONFIG=0x%08x -> 0x%08x\n",
392             XREAD4(sc, oper, XHCI_CONFIG), sc->sc_noslot);
393
394         XWRITE4(sc, oper, XHCI_CONFIG, sc->sc_noslot);
395
396         DPRINTF("Max slots: %u\n", sc->sc_noslot);
397
398         temp = XREAD4(sc, capa, XHCI_HCSPARAMS2);
399
400         sc->sc_noscratch = XHCI_HCS2_SPB_MAX(temp);
401
402         if (sc->sc_noscratch > XHCI_MAX_SCRATCHPADS) {
403                 device_printf(sc->sc_bus.parent, "XHCI request "
404                     "too many scratchpads\n");
405                 return (USB_ERR_NOMEM);
406         }
407
408         DPRINTF("Max scratch: %u\n", sc->sc_noscratch);
409
410         temp = XREAD4(sc, capa, XHCI_HCSPARAMS3);
411
412         sc->sc_exit_lat_max = XHCI_HCS3_U1_DEL(temp) +
413             XHCI_HCS3_U2_DEL(temp) + 250 /* us */;
414
415         temp = XREAD4(sc, oper, XHCI_USBSTS);
416
417         /* clear interrupts */
418         XWRITE4(sc, oper, XHCI_USBSTS, temp);
419         /* disable all device notifications */
420         XWRITE4(sc, oper, XHCI_DNCTRL, 0);
421
422         /* set up device context base address */
423         usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
424         pdctxa = buf_res.buffer;
425         memset(pdctxa, 0, sizeof(*pdctxa));
426
427         addr = buf_res.physaddr;
428         addr += (uintptr_t)&((struct xhci_dev_ctx_addr *)0)->qwSpBufPtr[0];
429
430         /* slot 0 points to the table of scratchpad pointers */
431         pdctxa->qwBaaDevCtxAddr[0] = htole64(addr);
432
433         for (i = 0; i != sc->sc_noscratch; i++) {
434                 struct usb_page_search buf_scp;
435                 usbd_get_page(&sc->sc_hw.scratch_pc[i], 0, &buf_scp);
436                 pdctxa->qwSpBufPtr[i] = htole64((uint64_t)buf_scp.physaddr);
437         }
438
439         addr = buf_res.physaddr;
440
441         XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
442         XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
443         XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
444         XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
445
446         /* Setup event table size */
447
448         temp = XREAD4(sc, capa, XHCI_HCSPARAMS2);
449
450         DPRINTF("HCS2=0x%08x\n", temp);
451
452         temp = XHCI_HCS2_ERST_MAX(temp);
453         temp = 1U << temp;
454         if (temp > XHCI_MAX_RSEG)
455                 temp = XHCI_MAX_RSEG;
456
457         sc->sc_erst_max = temp;
458
459         DPRINTF("ERSTSZ=0x%08x -> 0x%08x\n",
460             XREAD4(sc, runt, XHCI_ERSTSZ(0)), temp);
461
462         XWRITE4(sc, runt, XHCI_ERSTSZ(0), XHCI_ERSTS_SET(temp));
463
464         /* Check if we should use the default IMOD value */
465         if (sc->sc_imod_default == 0)
466                 sc->sc_imod_default = XHCI_IMOD_DEFAULT;
467
468         /* Setup interrupt rate */
469         XWRITE4(sc, runt, XHCI_IMOD(0), sc->sc_imod_default);
470
471         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
472
473         phwr = buf_res.buffer;
474         addr = buf_res.physaddr;
475         addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_events[0];
476
477         /* reset hardware root structure */
478         memset(phwr, 0, sizeof(*phwr));
479
480         phwr->hwr_ring_seg[0].qwEvrsTablePtr = htole64(addr);
481         phwr->hwr_ring_seg[0].dwEvrsTableSize = htole32(XHCI_MAX_EVENTS);
482
483         DPRINTF("ERDP(0)=0x%016llx\n", (unsigned long long)addr);
484
485         XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
486         XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
487
488         addr = buf_res.physaddr;
489
490         DPRINTF("ERSTBA(0)=0x%016llx\n", (unsigned long long)addr);
491
492         XWRITE4(sc, runt, XHCI_ERSTBA_LO(0), (uint32_t)addr);
493         XWRITE4(sc, runt, XHCI_ERSTBA_HI(0), (uint32_t)(addr >> 32));
494
495         /* Setup interrupter registers */
496
497         temp = XREAD4(sc, runt, XHCI_IMAN(0));
498         temp |= XHCI_IMAN_INTR_ENA;
499         XWRITE4(sc, runt, XHCI_IMAN(0), temp);
500
501         /* set up command ring control base address */
502         addr = buf_res.physaddr;
503         addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[0];
504
505         DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
506
507         XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
508         XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
509
510         phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
511
512         usb_bus_mem_flush_all(&sc->sc_bus, &xhci_iterate_hw_softc);
513
514         /* Go! */
515         XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_RS |
516             XHCI_CMD_INTE | XHCI_CMD_HSEE);
517
518         for (i = 0; i != 100; i++) {
519                 usb_pause_mtx(NULL, hz / 100);
520                 temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
521                 if (!temp)
522                         break;
523         }
524         if (temp) {
525                 XWRITE4(sc, oper, XHCI_USBCMD, 0);
526                 device_printf(sc->sc_bus.parent, "Run timeout.\n");
527                 return (USB_ERR_IOERROR);
528         }
529
530         /* catch any lost interrupts */
531         xhci_do_poll(&sc->sc_bus);
532
533         if (sc->sc_port_route != NULL) {
534                 /* Route all ports to the XHCI by default */
535                 sc->sc_port_route(sc->sc_bus.parent,
536                     ~xhciroute, xhciroute);
537         }
538         return (0);
539 }
540
541 usb_error_t
542 xhci_halt_controller(struct xhci_softc *sc)
543 {
544         uint32_t temp;
545         uint16_t i;
546
547         DPRINTF("\n");
548
549         sc->sc_capa_off = 0;
550         sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
551         sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0xF;
552         sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
553
554         /* Halt controller */
555         XWRITE4(sc, oper, XHCI_USBCMD, 0);
556
557         for (i = 0; i != 100; i++) {
558                 usb_pause_mtx(NULL, hz / 100);
559                 temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
560                 if (temp)
561                         break;
562         }
563
564         if (!temp) {
565                 device_printf(sc->sc_bus.parent, "Controller halt timeout.\n");
566                 return (USB_ERR_IOERROR);
567         }
568         return (0);
569 }
570
571 usb_error_t
572 xhci_init(struct xhci_softc *sc, device_t self)
573 {
574         uint32_t temp;
575
576         DPRINTF("\n");
577
578         /* initialize some bus fields */
579         sc->sc_bus.parent = self;
580
581         /* set the bus revision */
582         sc->sc_bus.usbrev = USB_REV_3_0;
583
584         /* set up the bus struct */
585         sc->sc_bus.methods = &xhci_bus_methods;
586
587         /* set up devices array */
588         sc->sc_bus.devices = sc->sc_devices;
589         sc->sc_bus.devices_max = XHCI_MAX_DEVICES;
590
591         /* set default cycle state in case of early interrupts */
592         sc->sc_event_ccs = 1;
593         sc->sc_command_ccs = 1;
594
595         /* set up bus space offsets */
596         sc->sc_capa_off = 0;
597         sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
598         sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0x1F;
599         sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
600
601         DPRINTF("CAPLENGTH=0x%x\n", sc->sc_oper_off);
602         DPRINTF("RUNTIMEOFFSET=0x%x\n", sc->sc_runt_off);
603         DPRINTF("DOOROFFSET=0x%x\n", sc->sc_door_off);
604
605         DPRINTF("xHCI version = 0x%04x\n", XREAD2(sc, capa, XHCI_HCIVERSION));
606
607         temp = XREAD4(sc, capa, XHCI_HCSPARAMS0);
608
609         DPRINTF("HCS0 = 0x%08x\n", temp);
610
611         /* set up context size */
612         if (XHCI_HCS0_CSZ(temp)) {
613                 sc->sc_ctx_is_64_byte = 1;
614         } else {
615                 sc->sc_ctx_is_64_byte = 0;
616         }
617
618         /* get DMA bits */
619         sc->sc_bus.dma_bits = XHCI_HCS0_AC64(temp) ? 64 : 32;
620
621         device_printf(self, "%d bytes context size, %d-bit DMA\n",
622             sc->sc_ctx_is_64_byte ? 64 : 32, (int)sc->sc_bus.dma_bits);
623
624         /* get all DMA memory */
625         if (usb_bus_mem_alloc_all(&sc->sc_bus,
626             USB_GET_DMA_TAG(self), &xhci_iterate_hw_softc)) {
627                 return (ENOMEM);
628         }
629
630         /* set up command queue mutex and condition varible */
631         cv_init(&sc->sc_cmd_cv, "CMDQ");
632         sx_init(&sc->sc_cmd_sx, "CMDQ lock");
633
634         if (usb_proc_create(&sc->sc_config_proc,
635             &sc->sc_bus.bus_mtx, device_get_nameunit(self), USB_PRI_MED)) {
636                 printf("WARNING: Creation of XHCI configure "
637                     "callback process failed.\n");
638         }
639         sc->sc_config_msg[0].hdr.pm_callback = &xhci_configure_msg;
640         sc->sc_config_msg[0].bus = &sc->sc_bus;
641         sc->sc_config_msg[1].hdr.pm_callback = &xhci_configure_msg;
642         sc->sc_config_msg[1].bus = &sc->sc_bus;
643
644         return (0);
645 }
646
647 void
648 xhci_uninit(struct xhci_softc *sc)
649 {
650         usb_proc_free(&sc->sc_config_proc);
651
652         usb_bus_mem_free_all(&sc->sc_bus, &xhci_iterate_hw_softc);
653
654         cv_destroy(&sc->sc_cmd_cv);
655         sx_destroy(&sc->sc_cmd_sx);
656 }
657
658 static void
659 xhci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state)
660 {
661         struct xhci_softc *sc = XHCI_BUS2SC(bus);
662
663         switch (state) {
664         case USB_HW_POWER_SUSPEND:
665                 DPRINTF("Stopping the XHCI\n");
666                 xhci_halt_controller(sc);
667                 break;
668         case USB_HW_POWER_SHUTDOWN:
669                 DPRINTF("Stopping the XHCI\n");
670                 xhci_halt_controller(sc);
671                 break;
672         case USB_HW_POWER_RESUME:
673                 DPRINTF("Starting the XHCI\n");
674                 xhci_start_controller(sc);
675                 break;
676         default:
677                 break;
678         }
679 }
680
681 static usb_error_t
682 xhci_generic_done_sub(struct usb_xfer *xfer)
683 {
684         struct xhci_td *td;
685         struct xhci_td *td_alt_next;
686         uint32_t len;
687         uint8_t status;
688
689         td = xfer->td_transfer_cache;
690         td_alt_next = td->alt_next;
691
692         if (xfer->aframes != xfer->nframes)
693                 usbd_xfer_set_frame_len(xfer, xfer->aframes, 0);
694
695         while (1) {
696
697                 usb_pc_cpu_invalidate(td->page_cache);
698
699                 status = td->status;
700                 len = td->remainder;
701
702                 DPRINTFN(4, "xfer=%p[%u/%u] rem=%u/%u status=%u\n",
703                     xfer, (unsigned int)xfer->aframes,
704                     (unsigned int)xfer->nframes,
705                     (unsigned int)len, (unsigned int)td->len,
706                     (unsigned int)status);
707
708                 /*
709                  * Verify the status length and
710                  * add the length to "frlengths[]":
711                  */
712                 if (len > td->len) {
713                         /* should not happen */
714                         DPRINTF("Invalid status length, "
715                             "0x%04x/0x%04x bytes\n", len, td->len);
716                         status = XHCI_TRB_ERROR_LENGTH;
717                 } else if (xfer->aframes != xfer->nframes) {
718                         xfer->frlengths[xfer->aframes] += td->len - len;
719                 }
720                 /* Check for last transfer */
721                 if (((void *)td) == xfer->td_transfer_last) {
722                         td = NULL;
723                         break;
724                 }
725                 /* Check for transfer error */
726                 if (status != XHCI_TRB_ERROR_SHORT_PKT &&
727                     status != XHCI_TRB_ERROR_SUCCESS) {
728                         /* the transfer is finished */
729                         td = NULL;
730                         break;
731                 }
732                 /* Check for short transfer */
733                 if (len > 0) {
734                         if (xfer->flags_int.short_frames_ok || 
735                             xfer->flags_int.isochronous_xfr ||
736                             xfer->flags_int.control_xfr) {
737                                 /* follow alt next */
738                                 td = td->alt_next;
739                         } else {
740                                 /* the transfer is finished */
741                                 td = NULL;
742                         }
743                         break;
744                 }
745                 td = td->obj_next;
746
747                 if (td->alt_next != td_alt_next) {
748                         /* this USB frame is complete */
749                         break;
750                 }
751         }
752
753         /* update transfer cache */
754
755         xfer->td_transfer_cache = td;
756
757         return ((status == XHCI_TRB_ERROR_STALL) ? USB_ERR_STALLED : 
758             (status != XHCI_TRB_ERROR_SHORT_PKT && 
759             status != XHCI_TRB_ERROR_SUCCESS) ? USB_ERR_IOERROR :
760             USB_ERR_NORMAL_COMPLETION);
761 }
762
763 static void
764 xhci_generic_done(struct usb_xfer *xfer)
765 {
766         usb_error_t err = 0;
767
768         DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
769             xfer, xfer->endpoint);
770
771         /* reset scanner */
772
773         xfer->td_transfer_cache = xfer->td_transfer_first;
774
775         if (xfer->flags_int.control_xfr) {
776
777                 if (xfer->flags_int.control_hdr)
778                         err = xhci_generic_done_sub(xfer);
779
780                 xfer->aframes = 1;
781
782                 if (xfer->td_transfer_cache == NULL)
783                         goto done;
784         }
785
786         while (xfer->aframes != xfer->nframes) {
787
788                 err = xhci_generic_done_sub(xfer);
789                 xfer->aframes++;
790
791                 if (xfer->td_transfer_cache == NULL)
792                         goto done;
793         }
794
795         if (xfer->flags_int.control_xfr &&
796             !xfer->flags_int.control_act)
797                 err = xhci_generic_done_sub(xfer);
798 done:
799         /* transfer is complete */
800         xhci_device_done(xfer, err);
801 }
802
803 static void
804 xhci_activate_transfer(struct usb_xfer *xfer)
805 {
806         struct xhci_td *td;
807
808         td = xfer->td_transfer_cache;
809
810         usb_pc_cpu_invalidate(td->page_cache);
811
812         if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
813
814                 /* activate the transfer */
815
816                 td->td_trb[0].dwTrb3 |= htole32(XHCI_TRB_3_CYCLE_BIT);
817                 usb_pc_cpu_flush(td->page_cache);
818
819                 xhci_endpoint_doorbell(xfer);
820         }
821 }
822
823 static void
824 xhci_skip_transfer(struct usb_xfer *xfer)
825 {
826         struct xhci_td *td;
827         struct xhci_td *td_last;
828
829         td = xfer->td_transfer_cache;
830         td_last = xfer->td_transfer_last;
831
832         td = td->alt_next;
833
834         usb_pc_cpu_invalidate(td->page_cache);
835
836         if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
837
838                 usb_pc_cpu_invalidate(td_last->page_cache);
839
840                 /* copy LINK TRB to current waiting location */
841
842                 td->td_trb[0].qwTrb0 = td_last->td_trb[td_last->ntrb].qwTrb0;
843                 td->td_trb[0].dwTrb2 = td_last->td_trb[td_last->ntrb].dwTrb2;
844                 usb_pc_cpu_flush(td->page_cache);
845
846                 td->td_trb[0].dwTrb3 = td_last->td_trb[td_last->ntrb].dwTrb3;
847                 usb_pc_cpu_flush(td->page_cache);
848
849                 xhci_endpoint_doorbell(xfer);
850         }
851 }
852
853 /*------------------------------------------------------------------------*
854  *      xhci_check_transfer
855  *------------------------------------------------------------------------*/
856 static void
857 xhci_check_transfer(struct xhci_softc *sc, struct xhci_trb *trb)
858 {
859         int64_t offset;
860         uint64_t td_event;
861         uint32_t temp;
862         uint32_t remainder;
863         uint8_t status;
864         uint8_t halted;
865         uint8_t epno;
866         uint8_t index;
867         uint8_t i;
868
869         /* decode TRB */
870         td_event = le64toh(trb->qwTrb0);
871         temp = le32toh(trb->dwTrb2);
872
873         remainder = XHCI_TRB_2_REM_GET(temp);
874         status = XHCI_TRB_2_ERROR_GET(temp);
875
876         temp = le32toh(trb->dwTrb3);
877         epno = XHCI_TRB_3_EP_GET(temp);
878         index = XHCI_TRB_3_SLOT_GET(temp);
879
880         /* check if error means halted */
881         halted = (status != XHCI_TRB_ERROR_SHORT_PKT &&
882             status != XHCI_TRB_ERROR_SUCCESS);
883
884         DPRINTF("slot=%u epno=%u remainder=%u status=%u\n",
885             index, epno, remainder, status);
886
887         if (index > sc->sc_noslot) {
888                 DPRINTF("Invalid slot.\n");
889                 return;
890         }
891
892         if ((epno == 0) || (epno >= XHCI_MAX_ENDPOINTS)) {
893                 DPRINTF("Invalid endpoint.\n");
894                 return;
895         }
896
897         /* try to find the USB transfer that generated the event */
898         for (i = 0; i != (XHCI_MAX_TRANSFERS - 1); i++) {
899                 struct usb_xfer *xfer;
900                 struct xhci_td *td;
901                 struct xhci_endpoint_ext *pepext;
902
903                 pepext = &sc->sc_hw.devs[index].endp[epno];
904
905                 xfer = pepext->xfer[i];
906                 if (xfer == NULL)
907                         continue;
908
909                 td = xfer->td_transfer_cache;
910
911                 DPRINTFN(5, "Checking if 0x%016llx == (0x%016llx .. 0x%016llx)\n",
912                         (long long)td_event,
913                         (long long)td->td_self,
914                         (long long)td->td_self + sizeof(td->td_trb));
915
916                 /*
917                  * NOTE: Some XHCI implementations might not trigger
918                  * an event on the last LINK TRB so we need to
919                  * consider both the last and second last event
920                  * address as conditions for a successful transfer.
921                  *
922                  * NOTE: We assume that the XHCI will only trigger one
923                  * event per chain of TRBs.
924                  */
925
926                 offset = td_event - td->td_self;
927
928                 if (offset >= 0 &&
929                     offset < (int64_t)sizeof(td->td_trb)) {
930
931                         usb_pc_cpu_invalidate(td->page_cache);
932
933                         /* compute rest of remainder, if any */
934                         for (i = (offset / 16) + 1; i < td->ntrb; i++) {
935                                 temp = le32toh(td->td_trb[i].dwTrb2);
936                                 remainder += XHCI_TRB_2_BYTES_GET(temp);
937                         }
938
939                         DPRINTFN(5, "New remainder: %u\n", remainder);
940
941                         /* clear isochronous transfer errors */
942                         if (xfer->flags_int.isochronous_xfr) {
943                                 if (halted) {
944                                         halted = 0;
945                                         status = XHCI_TRB_ERROR_SUCCESS;
946                                         remainder = td->len;
947                                 }
948                         }
949
950                         /* "td->remainder" is verified later */
951                         td->remainder = remainder;
952                         td->status = status;
953
954                         usb_pc_cpu_flush(td->page_cache);
955
956                         /*
957                          * 1) Last transfer descriptor makes the
958                          * transfer done
959                          */
960                         if (((void *)td) == xfer->td_transfer_last) {
961                                 DPRINTF("TD is last\n");
962                                 xhci_generic_done(xfer);
963                                 break;
964                         }
965
966                         /*
967                          * 2) Any kind of error makes the transfer
968                          * done
969                          */
970                         if (halted) {
971                                 DPRINTF("TD has I/O error\n");
972                                 xhci_generic_done(xfer);
973                                 break;
974                         }
975
976                         /*
977                          * 3) If there is no alternate next transfer,
978                          * a short packet also makes the transfer done
979                          */
980                         if (td->remainder > 0) {
981                                 if (td->alt_next == NULL) {
982                                         DPRINTF(
983                                             "short TD has no alternate next\n");
984                                         xhci_generic_done(xfer);
985                                         break;
986                                 }
987                                 DPRINTF("TD has short pkt\n");
988                                 if (xfer->flags_int.short_frames_ok ||
989                                     xfer->flags_int.isochronous_xfr ||
990                                     xfer->flags_int.control_xfr) {
991                                         /* follow the alt next */
992                                         xfer->td_transfer_cache = td->alt_next;
993                                         xhci_activate_transfer(xfer);
994                                         break;
995                                 }
996                                 xhci_skip_transfer(xfer);
997                                 xhci_generic_done(xfer);
998                                 break;
999                         }
1000
1001                         /*
1002                          * 4) Transfer complete - go to next TD
1003                          */
1004                         DPRINTF("Following next TD\n");
1005                         xfer->td_transfer_cache = td->obj_next;
1006                         xhci_activate_transfer(xfer);
1007                         break;          /* there should only be one match */
1008                 }
1009         }
1010 }
1011
1012 static int
1013 xhci_check_command(struct xhci_softc *sc, struct xhci_trb *trb)
1014 {
1015         if (sc->sc_cmd_addr == trb->qwTrb0) {
1016                 DPRINTF("Received command event\n");
1017                 sc->sc_cmd_result[0] = trb->dwTrb2;
1018                 sc->sc_cmd_result[1] = trb->dwTrb3;
1019                 cv_signal(&sc->sc_cmd_cv);
1020                 return (1);     /* command match */
1021         }
1022         return (0);
1023 }
1024
1025 static int
1026 xhci_interrupt_poll(struct xhci_softc *sc)
1027 {
1028         struct usb_page_search buf_res;
1029         struct xhci_hw_root *phwr;
1030         uint64_t addr;
1031         uint32_t temp;
1032         int retval = 0;
1033         uint16_t i;
1034         uint8_t event;
1035         uint8_t j;
1036         uint8_t k;
1037         uint8_t t;
1038
1039         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
1040
1041         phwr = buf_res.buffer;
1042
1043         /* Receive any events */
1044
1045         usb_pc_cpu_invalidate(&sc->sc_hw.root_pc);
1046
1047         i = sc->sc_event_idx;
1048         j = sc->sc_event_ccs;
1049         t = 2;
1050
1051         while (1) {
1052
1053                 temp = le32toh(phwr->hwr_events[i].dwTrb3);
1054
1055                 k = (temp & XHCI_TRB_3_CYCLE_BIT) ? 1 : 0;
1056
1057                 if (j != k)
1058                         break;
1059
1060                 event = XHCI_TRB_3_TYPE_GET(temp);
1061
1062                 DPRINTFN(10, "event[%u] = %u (0x%016llx 0x%08lx 0x%08lx)\n",
1063                     i, event, (long long)le64toh(phwr->hwr_events[i].qwTrb0),
1064                     (long)le32toh(phwr->hwr_events[i].dwTrb2),
1065                     (long)le32toh(phwr->hwr_events[i].dwTrb3));
1066
1067                 switch (event) {
1068                 case XHCI_TRB_EVENT_TRANSFER:
1069                         xhci_check_transfer(sc, &phwr->hwr_events[i]);
1070                         break;
1071                 case XHCI_TRB_EVENT_CMD_COMPLETE:
1072                         retval |= xhci_check_command(sc, &phwr->hwr_events[i]);
1073                         break;
1074                 default:
1075                         DPRINTF("Unhandled event = %u\n", event);
1076                         break;
1077                 }
1078
1079                 i++;
1080
1081                 if (i == XHCI_MAX_EVENTS) {
1082                         i = 0;
1083                         j ^= 1;
1084
1085                         /* check for timeout */
1086                         if (!--t)
1087                                 break;
1088                 }
1089         }
1090
1091         sc->sc_event_idx = i;
1092         sc->sc_event_ccs = j;
1093
1094         /*
1095          * NOTE: The Event Ring Dequeue Pointer Register is 64-bit
1096          * latched. That means to activate the register we need to
1097          * write both the low and high double word of the 64-bit
1098          * register.
1099          */
1100
1101         addr = buf_res.physaddr;
1102         addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_events[i];
1103
1104         /* try to clear busy bit */
1105         addr |= XHCI_ERDP_LO_BUSY;
1106
1107         XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
1108         XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
1109
1110         return (retval);
1111 }
1112
1113 static usb_error_t
1114 xhci_do_command(struct xhci_softc *sc, struct xhci_trb *trb, 
1115     uint16_t timeout_ms)
1116 {
1117         struct usb_page_search buf_res;
1118         struct xhci_hw_root *phwr;
1119         uint64_t addr;
1120         uint32_t temp;
1121         uint8_t i;
1122         uint8_t j;
1123         uint8_t timeout = 0;
1124         int err;
1125
1126         XHCI_CMD_ASSERT_LOCKED(sc);
1127
1128         /* get hardware root structure */
1129
1130         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
1131
1132         phwr = buf_res.buffer;
1133
1134         /* Queue command */
1135
1136         USB_BUS_LOCK(&sc->sc_bus);
1137 retry:
1138         i = sc->sc_command_idx;
1139         j = sc->sc_command_ccs;
1140
1141         DPRINTFN(10, "command[%u] = %u (0x%016llx, 0x%08lx, 0x%08lx)\n",
1142             i, XHCI_TRB_3_TYPE_GET(le32toh(trb->dwTrb3)),
1143             (long long)le64toh(trb->qwTrb0),
1144             (long)le32toh(trb->dwTrb2),
1145             (long)le32toh(trb->dwTrb3));
1146
1147         phwr->hwr_commands[i].qwTrb0 = trb->qwTrb0;
1148         phwr->hwr_commands[i].dwTrb2 = trb->dwTrb2;
1149
1150         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1151
1152         temp = trb->dwTrb3;
1153
1154         if (j)
1155                 temp |= htole32(XHCI_TRB_3_CYCLE_BIT);
1156         else
1157                 temp &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
1158
1159         temp &= ~htole32(XHCI_TRB_3_TC_BIT);
1160
1161         phwr->hwr_commands[i].dwTrb3 = temp;
1162
1163         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1164
1165         addr = buf_res.physaddr;
1166         addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[i];
1167
1168         sc->sc_cmd_addr = htole64(addr);
1169
1170         i++;
1171
1172         if (i == (XHCI_MAX_COMMANDS - 1)) {
1173
1174                 if (j) {
1175                         temp = htole32(XHCI_TRB_3_TC_BIT |
1176                             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
1177                             XHCI_TRB_3_CYCLE_BIT);
1178                 } else {
1179                         temp = htole32(XHCI_TRB_3_TC_BIT |
1180                             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
1181                 }
1182
1183                 phwr->hwr_commands[i].dwTrb3 = temp;
1184
1185                 usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1186
1187                 i = 0;
1188                 j ^= 1;
1189         }
1190
1191         sc->sc_command_idx = i;
1192         sc->sc_command_ccs = j;
1193
1194         XWRITE4(sc, door, XHCI_DOORBELL(0), 0);
1195
1196         err = cv_timedwait(&sc->sc_cmd_cv, &sc->sc_bus.bus_mtx,
1197             USB_MS_TO_TICKS(timeout_ms));
1198
1199         /*
1200          * In some error cases event interrupts are not generated.
1201          * Poll one time to see if the command has completed.
1202          */
1203         if (err != 0 && xhci_interrupt_poll(sc) != 0) {
1204                 DPRINTF("Command was completed when polling\n");
1205                 err = 0;
1206         }
1207         if (err != 0) {
1208                 DPRINTF("Command timeout!\n");
1209                 /*
1210                  * After some weeks of continuous operation, it has
1211                  * been observed that the ASMedia Technology, ASM1042
1212                  * SuperSpeed USB Host Controller can suddenly stop
1213                  * accepting commands via the command queue. Try to
1214                  * first reset the command queue. If that fails do a
1215                  * host controller reset.
1216                  */
1217                 if (timeout == 0 &&
1218                     xhci_reset_command_queue_locked(sc) == 0) {
1219                         temp = le32toh(trb->dwTrb3);
1220
1221                         /*
1222                          * Avoid infinite XHCI reset loops if the set
1223                          * address command fails to respond due to a
1224                          * non-enumerating device:
1225                          */
1226                         if (XHCI_TRB_3_TYPE_GET(temp) == XHCI_TRB_TYPE_ADDRESS_DEVICE &&
1227                             (temp & XHCI_TRB_3_BSR_BIT) == 0) {
1228                                 DPRINTF("Set address timeout\n");
1229                         } else {
1230                                 timeout = 1;
1231                                 goto retry;
1232                         }
1233                 } else {
1234                         DPRINTF("Controller reset!\n");
1235                         usb_bus_reset_async_locked(&sc->sc_bus);
1236                 }
1237                 err = USB_ERR_TIMEOUT;
1238                 trb->dwTrb2 = 0;
1239                 trb->dwTrb3 = 0;
1240         } else {
1241                 temp = le32toh(sc->sc_cmd_result[0]);
1242                 if (XHCI_TRB_2_ERROR_GET(temp) != XHCI_TRB_ERROR_SUCCESS)
1243                         err = USB_ERR_IOERROR;
1244
1245                 trb->dwTrb2 = sc->sc_cmd_result[0];
1246                 trb->dwTrb3 = sc->sc_cmd_result[1];
1247         }
1248
1249         USB_BUS_UNLOCK(&sc->sc_bus);
1250
1251         return (err);
1252 }
1253
1254 #if 0
1255 static usb_error_t
1256 xhci_cmd_nop(struct xhci_softc *sc)
1257 {
1258         struct xhci_trb trb;
1259         uint32_t temp;
1260
1261         DPRINTF("\n");
1262
1263         trb.qwTrb0 = 0;
1264         trb.dwTrb2 = 0;
1265         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NOOP);
1266
1267         trb.dwTrb3 = htole32(temp);
1268
1269         return (xhci_do_command(sc, &trb, 100 /* ms */));
1270 }
1271 #endif
1272
1273 static usb_error_t
1274 xhci_cmd_enable_slot(struct xhci_softc *sc, uint8_t *pslot)
1275 {
1276         struct xhci_trb trb;
1277         uint32_t temp;
1278         usb_error_t err;
1279
1280         DPRINTF("\n");
1281
1282         trb.qwTrb0 = 0;
1283         trb.dwTrb2 = 0;
1284         trb.dwTrb3 = htole32(XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT));
1285
1286         err = xhci_do_command(sc, &trb, 100 /* ms */);
1287         if (err)
1288                 goto done;
1289
1290         temp = le32toh(trb.dwTrb3);
1291
1292         *pslot = XHCI_TRB_3_SLOT_GET(temp); 
1293
1294 done:
1295         return (err);
1296 }
1297
1298 static usb_error_t
1299 xhci_cmd_disable_slot(struct xhci_softc *sc, uint8_t slot_id)
1300 {
1301         struct xhci_trb trb;
1302         uint32_t temp;
1303
1304         DPRINTF("\n");
1305
1306         trb.qwTrb0 = 0;
1307         trb.dwTrb2 = 0;
1308         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT) |
1309             XHCI_TRB_3_SLOT_SET(slot_id);
1310
1311         trb.dwTrb3 = htole32(temp);
1312
1313         return (xhci_do_command(sc, &trb, 100 /* ms */));
1314 }
1315
1316 static usb_error_t
1317 xhci_cmd_set_address(struct xhci_softc *sc, uint64_t input_ctx,
1318     uint8_t bsr, uint8_t slot_id)
1319 {
1320         struct xhci_trb trb;
1321         uint32_t temp;
1322
1323         DPRINTF("\n");
1324
1325         trb.qwTrb0 = htole64(input_ctx);
1326         trb.dwTrb2 = 0;
1327         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
1328             XHCI_TRB_3_SLOT_SET(slot_id);
1329
1330         if (bsr)
1331                 temp |= XHCI_TRB_3_BSR_BIT;
1332
1333         trb.dwTrb3 = htole32(temp);
1334
1335         return (xhci_do_command(sc, &trb, 500 /* ms */));
1336 }
1337
1338 static usb_error_t
1339 xhci_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t address)
1340 {
1341         struct usb_page_search buf_inp;
1342         struct usb_page_search buf_dev;
1343         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
1344         struct xhci_hw_dev *hdev;
1345         struct xhci_dev_ctx *pdev;
1346         struct xhci_endpoint_ext *pepext;
1347         uint32_t temp;
1348         uint16_t mps;
1349         usb_error_t err;
1350         uint8_t index;
1351
1352         /* the root HUB case is not handled here */
1353         if (udev->parent_hub == NULL)
1354                 return (USB_ERR_INVAL);
1355
1356         index = udev->controller_slot_id;
1357
1358         hdev =  &sc->sc_hw.devs[index];
1359
1360         if (mtx != NULL)
1361                 mtx_unlock(mtx);
1362
1363         XHCI_CMD_LOCK(sc);
1364
1365         switch (hdev->state) {
1366         case XHCI_ST_DEFAULT:
1367         case XHCI_ST_ENABLED:
1368
1369                 hdev->state = XHCI_ST_ENABLED;
1370
1371                 /* set configure mask to slot and EP0 */
1372                 xhci_configure_mask(udev, 3, 0);
1373
1374                 /* configure input slot context structure */
1375                 err = xhci_configure_device(udev);
1376
1377                 if (err != 0) {
1378                         DPRINTF("Could not configure device\n");
1379                         break;
1380                 }
1381
1382                 /* configure input endpoint context structure */
1383                 switch (udev->speed) {
1384                 case USB_SPEED_LOW:
1385                 case USB_SPEED_FULL:
1386                         mps = 8;
1387                         break;
1388                 case USB_SPEED_HIGH:
1389                         mps = 64;
1390                         break;
1391                 default:
1392                         mps = 512;
1393                         break;
1394                 }
1395
1396                 pepext = xhci_get_endpoint_ext(udev,
1397                     &udev->ctrl_ep_desc);
1398
1399                 /* ensure the control endpoint is setup again */
1400                 USB_BUS_LOCK(udev->bus);
1401                 pepext->trb_halted = 1;
1402                 pepext->trb_running = 0;
1403                 USB_BUS_UNLOCK(udev->bus);
1404
1405                 err = xhci_configure_endpoint(udev,
1406                     &udev->ctrl_ep_desc, pepext->physaddr,
1407                     0, 1, 1, 0, mps, mps);
1408
1409                 if (err != 0) {
1410                         DPRINTF("Could not configure default endpoint\n");
1411                         break;
1412                 }
1413
1414                 /* execute set address command */
1415                 usbd_get_page(&hdev->input_pc, 0, &buf_inp);
1416
1417                 err = xhci_cmd_set_address(sc, buf_inp.physaddr,
1418                     (address == 0), index);
1419
1420                 if (err != 0) {
1421                         temp = le32toh(sc->sc_cmd_result[0]);
1422                         if (address == 0 && sc->sc_port_route != NULL &&
1423                             XHCI_TRB_2_ERROR_GET(temp) ==
1424                             XHCI_TRB_ERROR_PARAMETER) {
1425                                 /* LynxPoint XHCI - ports are not switchable */
1426                                 /* Un-route all ports from the XHCI */
1427                                 sc->sc_port_route(sc->sc_bus.parent, 0, ~0);
1428                         }
1429                         DPRINTF("Could not set address "
1430                             "for slot %u.\n", index);
1431                         if (address != 0)
1432                                 break;
1433                 }
1434
1435                 /* update device address to new value */
1436
1437                 usbd_get_page(&hdev->device_pc, 0, &buf_dev);
1438                 pdev = buf_dev.buffer;
1439                 usb_pc_cpu_invalidate(&hdev->device_pc);
1440
1441                 temp = xhci_ctx_get_le32(sc, &pdev->ctx_slot.dwSctx3);
1442                 udev->address = XHCI_SCTX_3_DEV_ADDR_GET(temp);
1443
1444                 /* update device state to new value */
1445
1446                 if (address != 0)
1447                         hdev->state = XHCI_ST_ADDRESSED;
1448                 else
1449                         hdev->state = XHCI_ST_DEFAULT;
1450                 break;
1451
1452         default:
1453                 DPRINTF("Wrong state for set address.\n");
1454                 err = USB_ERR_IOERROR;
1455                 break;
1456         }
1457         XHCI_CMD_UNLOCK(sc);
1458
1459         if (mtx != NULL)
1460                 mtx_lock(mtx);
1461
1462         return (err);
1463 }
1464
1465 static usb_error_t
1466 xhci_cmd_configure_ep(struct xhci_softc *sc, uint64_t input_ctx,
1467     uint8_t deconfigure, uint8_t slot_id)
1468 {
1469         struct xhci_trb trb;
1470         uint32_t temp;
1471
1472         DPRINTF("\n");
1473
1474         trb.qwTrb0 = htole64(input_ctx);
1475         trb.dwTrb2 = 0;
1476         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP) |
1477             XHCI_TRB_3_SLOT_SET(slot_id);
1478
1479         if (deconfigure)
1480                 temp |= XHCI_TRB_3_DCEP_BIT;
1481
1482         trb.dwTrb3 = htole32(temp);
1483
1484         return (xhci_do_command(sc, &trb, 100 /* ms */));
1485 }
1486
1487 static usb_error_t
1488 xhci_cmd_evaluate_ctx(struct xhci_softc *sc, uint64_t input_ctx,
1489     uint8_t slot_id)
1490 {
1491         struct xhci_trb trb;
1492         uint32_t temp;
1493
1494         DPRINTF("\n");
1495
1496         trb.qwTrb0 = htole64(input_ctx);
1497         trb.dwTrb2 = 0;
1498         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX) |
1499             XHCI_TRB_3_SLOT_SET(slot_id);
1500         trb.dwTrb3 = htole32(temp);
1501
1502         return (xhci_do_command(sc, &trb, 100 /* ms */));
1503 }
1504
1505 static usb_error_t
1506 xhci_cmd_reset_ep(struct xhci_softc *sc, uint8_t preserve,
1507     uint8_t ep_id, uint8_t slot_id)
1508 {
1509         struct xhci_trb trb;
1510         uint32_t temp;
1511
1512         DPRINTF("\n");
1513
1514         trb.qwTrb0 = 0;
1515         trb.dwTrb2 = 0;
1516         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP) |
1517             XHCI_TRB_3_SLOT_SET(slot_id) |
1518             XHCI_TRB_3_EP_SET(ep_id);
1519
1520         if (preserve)
1521                 temp |= XHCI_TRB_3_PRSV_BIT;
1522
1523         trb.dwTrb3 = htole32(temp);
1524
1525         return (xhci_do_command(sc, &trb, 100 /* ms */));
1526 }
1527
1528 static usb_error_t
1529 xhci_cmd_set_tr_dequeue_ptr(struct xhci_softc *sc, uint64_t dequeue_ptr,
1530     uint16_t stream_id, uint8_t ep_id, uint8_t slot_id)
1531 {
1532         struct xhci_trb trb;
1533         uint32_t temp;
1534
1535         DPRINTF("\n");
1536
1537         trb.qwTrb0 = htole64(dequeue_ptr);
1538
1539         temp = XHCI_TRB_2_STREAM_SET(stream_id);
1540         trb.dwTrb2 = htole32(temp);
1541
1542         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE) |
1543             XHCI_TRB_3_SLOT_SET(slot_id) |
1544             XHCI_TRB_3_EP_SET(ep_id);
1545         trb.dwTrb3 = htole32(temp);
1546
1547         return (xhci_do_command(sc, &trb, 100 /* ms */));
1548 }
1549
1550 static usb_error_t
1551 xhci_cmd_stop_ep(struct xhci_softc *sc, uint8_t suspend,
1552     uint8_t ep_id, uint8_t slot_id)
1553 {
1554         struct xhci_trb trb;
1555         uint32_t temp;
1556
1557         DPRINTF("\n");
1558
1559         trb.qwTrb0 = 0;
1560         trb.dwTrb2 = 0;
1561         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP) |
1562             XHCI_TRB_3_SLOT_SET(slot_id) |
1563             XHCI_TRB_3_EP_SET(ep_id);
1564
1565         if (suspend)
1566                 temp |= XHCI_TRB_3_SUSP_EP_BIT;
1567
1568         trb.dwTrb3 = htole32(temp);
1569
1570         return (xhci_do_command(sc, &trb, 100 /* ms */));
1571 }
1572
1573 static usb_error_t
1574 xhci_cmd_reset_dev(struct xhci_softc *sc, uint8_t slot_id)
1575 {
1576         struct xhci_trb trb;
1577         uint32_t temp;
1578
1579         DPRINTF("\n");
1580
1581         trb.qwTrb0 = 0;
1582         trb.dwTrb2 = 0;
1583         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_DEVICE) |
1584             XHCI_TRB_3_SLOT_SET(slot_id);
1585
1586         trb.dwTrb3 = htole32(temp);
1587
1588         return (xhci_do_command(sc, &trb, 100 /* ms */));
1589 }
1590
1591 /*------------------------------------------------------------------------*
1592  *      xhci_interrupt - XHCI interrupt handler
1593  *------------------------------------------------------------------------*/
1594 void
1595 xhci_interrupt(struct xhci_softc *sc)
1596 {
1597         uint32_t status;
1598         uint32_t temp;
1599
1600         USB_BUS_LOCK(&sc->sc_bus);
1601
1602         status = XREAD4(sc, oper, XHCI_USBSTS);
1603
1604         /* acknowledge interrupts, if any */
1605         if (status != 0) {
1606                 XWRITE4(sc, oper, XHCI_USBSTS, status);
1607                 DPRINTFN(16, "real interrupt (status=0x%08x)\n", status);
1608         }
1609
1610         temp = XREAD4(sc, runt, XHCI_IMAN(0));
1611
1612         /* force clearing of pending interrupts */
1613         if (temp & XHCI_IMAN_INTR_PEND)
1614                 XWRITE4(sc, runt, XHCI_IMAN(0), temp);
1615  
1616         /* check for event(s) */
1617         xhci_interrupt_poll(sc);
1618
1619         if (status & (XHCI_STS_PCD | XHCI_STS_HCH |
1620             XHCI_STS_HSE | XHCI_STS_HCE)) {
1621
1622                 if (status & XHCI_STS_PCD) {
1623                         xhci_root_intr(sc);
1624                 }
1625
1626                 if (status & XHCI_STS_HCH) {
1627                         printf("%s: host controller halted\n",
1628                             __FUNCTION__);
1629                 }
1630
1631                 if (status & XHCI_STS_HSE) {
1632                         printf("%s: host system error\n",
1633                             __FUNCTION__);
1634                 }
1635
1636                 if (status & XHCI_STS_HCE) {
1637                         printf("%s: host controller error\n",
1638                            __FUNCTION__);
1639                 }
1640         }
1641         USB_BUS_UNLOCK(&sc->sc_bus);
1642 }
1643
1644 /*------------------------------------------------------------------------*
1645  *      xhci_timeout - XHCI timeout handler
1646  *------------------------------------------------------------------------*/
1647 static void
1648 xhci_timeout(void *arg)
1649 {
1650         struct usb_xfer *xfer = arg;
1651
1652         DPRINTF("xfer=%p\n", xfer);
1653
1654         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1655
1656         /* transfer is transferred */
1657         xhci_device_done(xfer, USB_ERR_TIMEOUT);
1658 }
1659
1660 static void
1661 xhci_do_poll(struct usb_bus *bus)
1662 {
1663         struct xhci_softc *sc = XHCI_BUS2SC(bus);
1664
1665         USB_BUS_LOCK(&sc->sc_bus);
1666         xhci_interrupt_poll(sc);
1667         USB_BUS_UNLOCK(&sc->sc_bus);
1668 }
1669
1670 static void
1671 xhci_setup_generic_chain_sub(struct xhci_std_temp *temp)
1672 {
1673         struct usb_page_search buf_res;
1674         struct xhci_td *td;
1675         struct xhci_td *td_next;
1676         struct xhci_td *td_alt_next;
1677         struct xhci_td *td_first;
1678         uint32_t buf_offset;
1679         uint32_t average;
1680         uint32_t len_old;
1681         uint32_t npkt_off;
1682         uint32_t dword;
1683         uint8_t shortpkt_old;
1684         uint8_t precompute;
1685         uint8_t x;
1686
1687         td_alt_next = NULL;
1688         buf_offset = 0;
1689         shortpkt_old = temp->shortpkt;
1690         len_old = temp->len;
1691         npkt_off = 0;
1692         precompute = 1;
1693
1694 restart:
1695
1696         td = temp->td;
1697         td_next = td_first = temp->td_next;
1698
1699         while (1) {
1700
1701                 if (temp->len == 0) {
1702
1703                         if (temp->shortpkt)
1704                                 break;
1705
1706                         /* send a Zero Length Packet, ZLP, last */
1707
1708                         temp->shortpkt = 1;
1709                         average = 0;
1710
1711                 } else {
1712
1713                         average = temp->average;
1714
1715                         if (temp->len < average) {
1716                                 if (temp->len % temp->max_packet_size) {
1717                                         temp->shortpkt = 1;
1718                                 }
1719                                 average = temp->len;
1720                         }
1721                 }
1722
1723                 if (td_next == NULL)
1724                         panic("%s: out of XHCI transfer descriptors!", __FUNCTION__);
1725
1726                 /* get next TD */
1727
1728                 td = td_next;
1729                 td_next = td->obj_next;
1730
1731                 /* check if we are pre-computing */
1732
1733                 if (precompute) {
1734
1735                         /* update remaining length */
1736
1737                         temp->len -= average;
1738
1739                         continue;
1740                 }
1741                 /* fill out current TD */
1742
1743                 td->len = average;
1744                 td->remainder = 0;
1745                 td->status = 0;
1746
1747                 /* update remaining length */
1748
1749                 temp->len -= average;
1750
1751                 /* reset TRB index */
1752
1753                 x = 0;
1754
1755                 if (temp->trb_type == XHCI_TRB_TYPE_SETUP_STAGE) {
1756                         /* immediate data */
1757
1758                         if (average > 8)
1759                                 average = 8;
1760
1761                         td->td_trb[0].qwTrb0 = 0;
1762
1763                         usbd_copy_out(temp->pc, temp->offset + buf_offset, 
1764                            (uint8_t *)(uintptr_t)&td->td_trb[0].qwTrb0,
1765                            average);
1766
1767                         dword = XHCI_TRB_2_BYTES_SET(8) |
1768                             XHCI_TRB_2_TDSZ_SET(0) |
1769                             XHCI_TRB_2_IRQ_SET(0);
1770
1771                         td->td_trb[0].dwTrb2 = htole32(dword);
1772
1773                         dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
1774                           XHCI_TRB_3_IDT_BIT | XHCI_TRB_3_CYCLE_BIT;
1775
1776                         /* check wLength */
1777                         if (td->td_trb[0].qwTrb0 &
1778                            htole64(XHCI_TRB_0_WLENGTH_MASK)) {
1779                                 if (td->td_trb[0].qwTrb0 &
1780                                     htole64(XHCI_TRB_0_DIR_IN_MASK))
1781                                         dword |= XHCI_TRB_3_TRT_IN;
1782                                 else
1783                                         dword |= XHCI_TRB_3_TRT_OUT;
1784                         }
1785
1786                         td->td_trb[0].dwTrb3 = htole32(dword);
1787 #ifdef USB_DEBUG
1788                         xhci_dump_trb(&td->td_trb[x]);
1789 #endif
1790                         x++;
1791
1792                 } else do {
1793
1794                         uint32_t npkt;
1795
1796                         /* fill out buffer pointers */
1797
1798                         if (average == 0) {
1799                                 memset(&buf_res, 0, sizeof(buf_res));
1800                         } else {
1801                                 usbd_get_page(temp->pc, temp->offset +
1802                                     buf_offset, &buf_res);
1803
1804                                 /* get length to end of page */
1805                                 if (buf_res.length > average)
1806                                         buf_res.length = average;
1807
1808                                 /* check for maximum length */
1809                                 if (buf_res.length > XHCI_TD_PAGE_SIZE)
1810                                         buf_res.length = XHCI_TD_PAGE_SIZE;
1811
1812                                 npkt_off += buf_res.length;
1813                         }
1814
1815                         /* set up npkt */
1816                         npkt = (len_old - npkt_off + temp->max_packet_size - 1) /
1817                             temp->max_packet_size;
1818
1819                         if (npkt == 0)
1820                                 npkt = 1;
1821                         else if (npkt > 31)
1822                                 npkt = 31;
1823
1824                         /* fill out TRB's */
1825                         td->td_trb[x].qwTrb0 =
1826                             htole64((uint64_t)buf_res.physaddr);
1827
1828                         dword =
1829                           XHCI_TRB_2_BYTES_SET(buf_res.length) |
1830                           XHCI_TRB_2_TDSZ_SET(npkt) | 
1831                           XHCI_TRB_2_IRQ_SET(0);
1832
1833                         td->td_trb[x].dwTrb2 = htole32(dword);
1834
1835                         switch (temp->trb_type) {
1836                         case XHCI_TRB_TYPE_ISOCH:
1837                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1838                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
1839                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1840                                 if (td != td_first) {
1841                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
1842                                 } else if (temp->do_isoc_sync != 0) {
1843                                         temp->do_isoc_sync = 0;
1844                                         /* wait until "isoc_frame" */
1845                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1846                                             XHCI_TRB_3_FRID_SET(temp->isoc_frame / 8);
1847                                 } else {
1848                                         /* start data transfer at next interval */
1849                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1850                                             XHCI_TRB_3_ISO_SIA_BIT;
1851                                 }
1852                                 if (temp->direction == UE_DIR_IN)
1853                                         dword |= XHCI_TRB_3_ISP_BIT;
1854                                 break;
1855                         case XHCI_TRB_TYPE_DATA_STAGE:
1856                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1857                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE);
1858                                 if (temp->direction == UE_DIR_IN)
1859                                         dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
1860                                 /*
1861                                  * Section 3.2.9 in the XHCI
1862                                  * specification about control
1863                                  * transfers says that we should use a
1864                                  * normal-TRB if there are more TRBs
1865                                  * extending the data-stage
1866                                  * TRB. Update the "trb_type".
1867                                  */
1868                                 temp->trb_type = XHCI_TRB_TYPE_NORMAL;
1869                                 break;
1870                         case XHCI_TRB_TYPE_STATUS_STAGE:
1871                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1872                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE);
1873                                 if (temp->direction == UE_DIR_IN)
1874                                         dword |= XHCI_TRB_3_DIR_IN;
1875                                 break;
1876                         default:        /* XHCI_TRB_TYPE_NORMAL */
1877                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1878                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
1879                                 if (temp->direction == UE_DIR_IN)
1880                                         dword |= XHCI_TRB_3_ISP_BIT;
1881                                 break;
1882                         }
1883                         td->td_trb[x].dwTrb3 = htole32(dword);
1884
1885                         average -= buf_res.length;
1886                         buf_offset += buf_res.length;
1887 #ifdef USB_DEBUG
1888                         xhci_dump_trb(&td->td_trb[x]);
1889 #endif
1890                         x++;
1891
1892                 } while (average != 0);
1893
1894                 td->td_trb[x-1].dwTrb3 |= htole32(XHCI_TRB_3_IOC_BIT);
1895
1896                 /* store number of data TRB's */
1897
1898                 td->ntrb = x;
1899
1900                 DPRINTF("NTRB=%u\n", x);
1901
1902                 /* fill out link TRB */
1903
1904                 if (td_next != NULL) {
1905                         /* link the current TD with the next one */
1906                         td->td_trb[x].qwTrb0 = htole64((uint64_t)td_next->td_self);
1907                         DPRINTF("LINK=0x%08llx\n", (long long)td_next->td_self);
1908                 } else {
1909                         /* this field will get updated later */
1910                         DPRINTF("NOLINK\n");
1911                 }
1912
1913                 dword = XHCI_TRB_2_IRQ_SET(0);
1914
1915                 td->td_trb[x].dwTrb2 = htole32(dword);
1916
1917                 dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
1918                     XHCI_TRB_3_CYCLE_BIT | XHCI_TRB_3_IOC_BIT |
1919                     /*
1920                      * CHAIN-BIT: Ensure that a multi-TRB IN-endpoint
1921                      * frame only receives a single short packet event
1922                      * by setting the CHAIN bit in the LINK field. In
1923                      * addition some XHCI controllers have problems
1924                      * sending a ZLP unless the CHAIN-BIT is set in
1925                      * the LINK TRB.
1926                      */
1927                     XHCI_TRB_3_CHAIN_BIT;
1928
1929                 td->td_trb[x].dwTrb3 = htole32(dword);
1930
1931                 td->alt_next = td_alt_next;
1932 #ifdef USB_DEBUG
1933                 xhci_dump_trb(&td->td_trb[x]);
1934 #endif
1935                 usb_pc_cpu_flush(td->page_cache);
1936         }
1937
1938         if (precompute) {
1939                 precompute = 0;
1940
1941                 /* set up alt next pointer, if any */
1942                 if (temp->last_frame) {
1943                         td_alt_next = NULL;
1944                 } else {
1945                         /* we use this field internally */
1946                         td_alt_next = td_next;
1947                 }
1948
1949                 /* restore */
1950                 temp->shortpkt = shortpkt_old;
1951                 temp->len = len_old;
1952                 goto restart;
1953         }
1954
1955         /*
1956          * Remove cycle bit from the first TRB if we are
1957          * stepping them:
1958          */
1959         if (temp->step_td != 0) {
1960                 td_first->td_trb[0].dwTrb3 &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
1961                 usb_pc_cpu_flush(td_first->page_cache);
1962         }
1963
1964         /* clear TD SIZE to zero, hence this is the last TRB */
1965         /* remove chain bit because this is the last data TRB in the chain */
1966         td->td_trb[td->ntrb - 1].dwTrb2 &= ~htole32(XHCI_TRB_2_TDSZ_SET(15));
1967         td->td_trb[td->ntrb - 1].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
1968         /* remove CHAIN-BIT from last LINK TRB */
1969         td->td_trb[td->ntrb].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
1970
1971         usb_pc_cpu_flush(td->page_cache);
1972
1973         temp->td = td;
1974         temp->td_next = td_next;
1975 }
1976
1977 static void
1978 xhci_setup_generic_chain(struct usb_xfer *xfer)
1979 {
1980         struct xhci_std_temp temp;
1981         struct xhci_td *td;
1982         uint32_t x;
1983         uint32_t y;
1984         uint8_t mult;
1985
1986         temp.do_isoc_sync = 0;
1987         temp.step_td = 0;
1988         temp.tbc = 0;
1989         temp.tlbpc = 0;
1990         temp.average = xfer->max_hc_frame_size;
1991         temp.max_packet_size = xfer->max_packet_size;
1992         temp.sc = XHCI_BUS2SC(xfer->xroot->bus);
1993         temp.pc = NULL;
1994         temp.last_frame = 0;
1995         temp.offset = 0;
1996         temp.multishort = xfer->flags_int.isochronous_xfr ||
1997             xfer->flags_int.control_xfr ||
1998             xfer->flags_int.short_frames_ok;
1999
2000         /* toggle the DMA set we are using */
2001         xfer->flags_int.curr_dma_set ^= 1;
2002
2003         /* get next DMA set */
2004         td = xfer->td_start[xfer->flags_int.curr_dma_set];
2005
2006         temp.td = NULL;
2007         temp.td_next = td;
2008
2009         xfer->td_transfer_first = td;
2010         xfer->td_transfer_cache = td;
2011
2012         if (xfer->flags_int.isochronous_xfr) {
2013                 uint8_t shift;
2014
2015                 /* compute multiplier for ISOCHRONOUS transfers */
2016                 mult = xfer->endpoint->ecomp ?
2017                     (xfer->endpoint->ecomp->bmAttributes & 3) : 0;
2018                 /* check for USB 2.0 multiplier */
2019                 if (mult == 0) {
2020                         mult = (xfer->endpoint->edesc->
2021                             wMaxPacketSize[1] >> 3) & 3;
2022                 }
2023                 /* range check */
2024                 if (mult > 2)
2025                         mult = 3;
2026                 else
2027                         mult++;
2028
2029                 x = XREAD4(temp.sc, runt, XHCI_MFINDEX);
2030
2031                 DPRINTF("MFINDEX=0x%08x\n", x);
2032
2033                 switch (usbd_get_speed(xfer->xroot->udev)) {
2034                 case USB_SPEED_FULL:
2035                         shift = 3;
2036                         temp.isoc_delta = 8;    /* 1ms */
2037                         x += temp.isoc_delta - 1;
2038                         x &= ~(temp.isoc_delta - 1);
2039                         break;
2040                 default:
2041                         shift = usbd_xfer_get_fps_shift(xfer);
2042                         temp.isoc_delta = 1U << shift;
2043                         x += temp.isoc_delta - 1;
2044                         x &= ~(temp.isoc_delta - 1);
2045                         /* simple frame load balancing */
2046                         x += xfer->endpoint->usb_uframe;
2047                         break;
2048                 }
2049
2050                 y = XHCI_MFINDEX_GET(x - xfer->endpoint->isoc_next);
2051
2052                 if ((xfer->endpoint->is_synced == 0) ||
2053                     (y < (xfer->nframes << shift)) ||
2054                     (XHCI_MFINDEX_GET(-y) >= (128 * 8))) {
2055                         /*
2056                          * If there is data underflow or the pipe
2057                          * queue is empty we schedule the transfer a
2058                          * few frames ahead of the current frame
2059                          * position. Else two isochronous transfers
2060                          * might overlap.
2061                          */
2062                         xfer->endpoint->isoc_next = XHCI_MFINDEX_GET(x + (3 * 8));
2063                         xfer->endpoint->is_synced = 1;
2064                         temp.do_isoc_sync = 1;
2065
2066                         DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next);
2067                 }
2068
2069                 /* compute isochronous completion time */
2070
2071                 y = XHCI_MFINDEX_GET(xfer->endpoint->isoc_next - (x & ~7));
2072
2073                 xfer->isoc_time_complete =
2074                     usb_isoc_time_expand(&temp.sc->sc_bus, x / 8) +
2075                     (y / 8) + (((xfer->nframes << shift) + 7) / 8);
2076
2077                 x = 0;
2078                 temp.isoc_frame = xfer->endpoint->isoc_next;
2079                 temp.trb_type = XHCI_TRB_TYPE_ISOCH;
2080
2081                 xfer->endpoint->isoc_next += xfer->nframes << shift;
2082
2083         } else if (xfer->flags_int.control_xfr) {
2084
2085                 /* check if we should prepend a setup message */
2086
2087                 if (xfer->flags_int.control_hdr) {
2088
2089                         temp.len = xfer->frlengths[0];
2090                         temp.pc = xfer->frbuffers + 0;
2091                         temp.shortpkt = temp.len ? 1 : 0;
2092                         temp.trb_type = XHCI_TRB_TYPE_SETUP_STAGE;
2093                         temp.direction = 0;
2094
2095                         /* check for last frame */
2096                         if (xfer->nframes == 1) {
2097                                 /* no STATUS stage yet, SETUP is last */
2098                                 if (xfer->flags_int.control_act)
2099                                         temp.last_frame = 1;
2100                         }
2101
2102                         xhci_setup_generic_chain_sub(&temp);
2103                 }
2104                 x = 1;
2105                 mult = 1;
2106                 temp.isoc_delta = 0;
2107                 temp.isoc_frame = 0;
2108                 temp.trb_type = xfer->flags_int.control_did_data ?
2109                     XHCI_TRB_TYPE_NORMAL : XHCI_TRB_TYPE_DATA_STAGE;
2110         } else {
2111                 x = 0;
2112                 mult = 1;
2113                 temp.isoc_delta = 0;
2114                 temp.isoc_frame = 0;
2115                 temp.trb_type = XHCI_TRB_TYPE_NORMAL;
2116         }
2117
2118         if (x != xfer->nframes) {
2119                 /* set up page_cache pointer */
2120                 temp.pc = xfer->frbuffers + x;
2121                 /* set endpoint direction */
2122                 temp.direction = UE_GET_DIR(xfer->endpointno);
2123         }
2124
2125         while (x != xfer->nframes) {
2126
2127                 /* DATA0 / DATA1 message */
2128
2129                 temp.len = xfer->frlengths[x];
2130                 temp.step_td = ((xfer->endpointno & UE_DIR_IN) &&
2131                     x != 0 && temp.multishort == 0);
2132
2133                 x++;
2134
2135                 if (x == xfer->nframes) {
2136                         if (xfer->flags_int.control_xfr) {
2137                                 /* no STATUS stage yet, DATA is last */
2138                                 if (xfer->flags_int.control_act)
2139                                         temp.last_frame = 1;
2140                         } else {
2141                                 temp.last_frame = 1;
2142                         }
2143                 }
2144                 if (temp.len == 0) {
2145
2146                         /* make sure that we send an USB packet */
2147
2148                         temp.shortpkt = 0;
2149
2150                         temp.tbc = 0;
2151                         temp.tlbpc = mult - 1;
2152
2153                 } else if (xfer->flags_int.isochronous_xfr) {
2154
2155                         uint8_t tdpc;
2156
2157                         /*
2158                          * Isochronous transfers don't have short
2159                          * packet termination:
2160                          */
2161
2162                         temp.shortpkt = 1;
2163
2164                         /* isochronous transfers have a transfer limit */
2165
2166                         if (temp.len > xfer->max_frame_size)
2167                                 temp.len = xfer->max_frame_size;
2168
2169                         /* compute TD packet count */
2170                         tdpc = (temp.len + xfer->max_packet_size - 1) /
2171                             xfer->max_packet_size;
2172
2173                         temp.tbc = ((tdpc + mult - 1) / mult) - 1;
2174                         temp.tlbpc = (tdpc % mult);
2175
2176                         if (temp.tlbpc == 0)
2177                                 temp.tlbpc = mult - 1;
2178                         else
2179                                 temp.tlbpc--;
2180                 } else {
2181
2182                         /* regular data transfer */
2183
2184                         temp.shortpkt = xfer->flags.force_short_xfer ? 0 : 1;
2185                 }
2186
2187                 xhci_setup_generic_chain_sub(&temp);
2188
2189                 if (xfer->flags_int.isochronous_xfr) {
2190                         temp.offset += xfer->frlengths[x - 1];
2191                         temp.isoc_frame += temp.isoc_delta;
2192                 } else {
2193                         /* get next Page Cache pointer */
2194                         temp.pc = xfer->frbuffers + x;
2195                 }
2196         }
2197
2198         /* check if we should append a status stage */
2199
2200         if (xfer->flags_int.control_xfr &&
2201             !xfer->flags_int.control_act) {
2202
2203                 /*
2204                  * Send a DATA1 message and invert the current
2205                  * endpoint direction.
2206                  */
2207                 temp.step_td = (xfer->nframes != 0);
2208                 temp.direction = UE_GET_DIR(xfer->endpointno) ^ UE_DIR_IN;
2209                 temp.len = 0;
2210                 temp.pc = NULL;
2211                 temp.shortpkt = 0;
2212                 temp.last_frame = 1;
2213                 temp.trb_type = XHCI_TRB_TYPE_STATUS_STAGE;
2214
2215                 xhci_setup_generic_chain_sub(&temp);
2216         }
2217
2218         td = temp.td;
2219
2220         /* must have at least one frame! */
2221
2222         xfer->td_transfer_last = td;
2223
2224         DPRINTF("first=%p last=%p\n", xfer->td_transfer_first, td);
2225 }
2226
2227 static void
2228 xhci_set_slot_pointer(struct xhci_softc *sc, uint8_t index, uint64_t dev_addr)
2229 {
2230         struct usb_page_search buf_res;
2231         struct xhci_dev_ctx_addr *pdctxa;
2232
2233         usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
2234
2235         pdctxa = buf_res.buffer;
2236
2237         DPRINTF("addr[%u]=0x%016llx\n", index, (long long)dev_addr);
2238
2239         pdctxa->qwBaaDevCtxAddr[index] = htole64(dev_addr);
2240
2241         usb_pc_cpu_flush(&sc->sc_hw.ctx_pc);
2242 }
2243
2244 static usb_error_t
2245 xhci_configure_mask(struct usb_device *udev, uint32_t mask, uint8_t drop)
2246 {
2247         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2248         struct usb_page_search buf_inp;
2249         struct xhci_input_dev_ctx *pinp;
2250         uint32_t temp;
2251         uint8_t index;
2252         uint8_t x;
2253
2254         index = udev->controller_slot_id;
2255
2256         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2257
2258         pinp = buf_inp.buffer;
2259
2260         if (drop) {
2261                 mask &= XHCI_INCTX_NON_CTRL_MASK;
2262                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0, mask);
2263                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, 0);
2264         } else {
2265                 /*
2266                  * Some hardware requires that we drop the endpoint
2267                  * context before adding it again:
2268                  */
2269                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0,
2270                     mask & XHCI_INCTX_NON_CTRL_MASK);
2271
2272                 /* Add new endpoint context */
2273                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, mask);
2274
2275                 /* find most significant set bit */
2276                 for (x = 31; x != 1; x--) {
2277                         if (mask & (1 << x))
2278                                 break;
2279                 }
2280
2281                 /* adjust */
2282                 x--;
2283
2284                 /* figure out the maximum number of contexts */
2285                 if (x > sc->sc_hw.devs[index].context_num)
2286                         sc->sc_hw.devs[index].context_num = x;
2287                 else
2288                         x = sc->sc_hw.devs[index].context_num;
2289
2290                 /* update number of contexts */
2291                 temp = xhci_ctx_get_le32(sc, &pinp->ctx_slot.dwSctx0);
2292                 temp &= ~XHCI_SCTX_0_CTX_NUM_SET(31);
2293                 temp |= XHCI_SCTX_0_CTX_NUM_SET(x + 1);
2294                 xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2295         }
2296         usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2297         return (0);
2298 }
2299
2300 static usb_error_t
2301 xhci_configure_endpoint(struct usb_device *udev,
2302     struct usb_endpoint_descriptor *edesc, uint64_t ring_addr,
2303     uint16_t interval, uint8_t max_packet_count, uint8_t mult,
2304     uint8_t fps_shift, uint16_t max_packet_size, uint16_t max_frame_size)
2305 {
2306         struct usb_page_search buf_inp;
2307         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2308         struct xhci_input_dev_ctx *pinp;
2309         uint32_t temp;
2310         uint8_t index;
2311         uint8_t epno;
2312         uint8_t type;
2313
2314         index = udev->controller_slot_id;
2315
2316         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2317
2318         pinp = buf_inp.buffer;
2319
2320         epno = edesc->bEndpointAddress;
2321         type = edesc->bmAttributes & UE_XFERTYPE;
2322
2323         if (type == UE_CONTROL)
2324                 epno |= UE_DIR_IN;
2325
2326         epno = XHCI_EPNO2EPID(epno);
2327
2328         if (epno == 0)
2329                 return (USB_ERR_NO_PIPE);               /* invalid */
2330
2331         if (max_packet_count == 0)
2332                 return (USB_ERR_BAD_BUFSIZE);
2333
2334         max_packet_count--;
2335
2336         if (mult == 0)
2337                 return (USB_ERR_BAD_BUFSIZE);
2338
2339         temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2340             XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
2341             XHCI_EPCTX_0_LSA_SET(0);
2342
2343         switch (udev->speed) {
2344         case USB_SPEED_FULL:
2345         case USB_SPEED_LOW:
2346                 /* 1ms -> 125us */
2347                 fps_shift += 3;
2348                 break;
2349         default:
2350                 break;
2351         }
2352
2353         switch (type) {
2354         case UE_INTERRUPT:
2355                 if (fps_shift > 3)
2356                         fps_shift--;
2357                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2358                 break;
2359         case UE_ISOCHRONOUS:
2360                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2361
2362                 switch (udev->speed) {
2363                 case USB_SPEED_SUPER:
2364                         if (mult > 3)
2365                                 mult = 3;
2366                         temp |= XHCI_EPCTX_0_MULT_SET(mult - 1);
2367                         max_packet_count /= mult;
2368                         break;
2369                 default:
2370                         break;
2371                 }
2372                 break;
2373         default:
2374                 break;
2375         }
2376
2377         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx0, temp);
2378
2379         temp =
2380             XHCI_EPCTX_1_HID_SET(0) |
2381             XHCI_EPCTX_1_MAXB_SET(max_packet_count) |
2382             XHCI_EPCTX_1_MAXP_SIZE_SET(max_packet_size);
2383
2384         /*
2385          * Always enable the "three strikes and you are gone" feature
2386          * except for ISOCHRONOUS endpoints. This is suggested by
2387          * section 4.3.3 in the XHCI specification about device slot
2388          * initialisation.
2389          */
2390         if (type != UE_ISOCHRONOUS)
2391                 temp |= XHCI_EPCTX_1_CERR_SET(3);
2392
2393         switch (type) {
2394         case UE_CONTROL:
2395                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2396                 break;
2397         case UE_ISOCHRONOUS:
2398                 temp |= XHCI_EPCTX_1_EPTYPE_SET(1);
2399                 break;
2400         case UE_BULK:
2401                 temp |= XHCI_EPCTX_1_EPTYPE_SET(2);
2402                 break;
2403         default:
2404                 temp |= XHCI_EPCTX_1_EPTYPE_SET(3);
2405                 break;
2406         }
2407
2408         /* check for IN direction */
2409         if (epno & 1)
2410                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2411
2412         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx1, temp);
2413
2414         ring_addr |= XHCI_EPCTX_2_DCS_SET(1);
2415
2416         xhci_ctx_set_le64(sc, &pinp->ctx_ep[epno - 1].qwEpCtx2, ring_addr);
2417
2418         switch (edesc->bmAttributes & UE_XFERTYPE) {
2419         case UE_INTERRUPT:
2420         case UE_ISOCHRONOUS:
2421                 temp = XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(max_frame_size) |
2422                     XHCI_EPCTX_4_AVG_TRB_LEN_SET(MIN(XHCI_PAGE_SIZE,
2423                     max_frame_size));
2424                 break;
2425         case UE_CONTROL:
2426                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8);
2427                 break;
2428         default:
2429                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(XHCI_PAGE_SIZE);
2430                 break;
2431         }
2432
2433         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx4, temp);
2434
2435 #ifdef USB_DEBUG
2436         xhci_dump_endpoint(sc, &pinp->ctx_ep[epno - 1]);
2437 #endif
2438         usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2439
2440         return (0);             /* success */
2441 }
2442
2443 static usb_error_t
2444 xhci_configure_endpoint_by_xfer(struct usb_xfer *xfer)
2445 {
2446         struct xhci_endpoint_ext *pepext;
2447         struct usb_endpoint_ss_comp_descriptor *ecomp;
2448
2449         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2450             xfer->endpoint->edesc);
2451
2452         ecomp = xfer->endpoint->ecomp;
2453
2454         pepext->trb[0].dwTrb3 = 0;      /* halt any transfers */
2455         usb_pc_cpu_flush(pepext->page_cache);
2456
2457         return (xhci_configure_endpoint(xfer->xroot->udev,
2458             xfer->endpoint->edesc, pepext->physaddr,
2459             xfer->interval, xfer->max_packet_count,
2460             (ecomp != NULL) ? (ecomp->bmAttributes & 3) + 1 : 1,
2461             usbd_xfer_get_fps_shift(xfer), xfer->max_packet_size,
2462             xfer->max_frame_size));
2463 }
2464
2465 static usb_error_t
2466 xhci_configure_device(struct usb_device *udev)
2467 {
2468         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2469         struct usb_page_search buf_inp;
2470         struct usb_page_cache *pcinp;
2471         struct xhci_input_dev_ctx *pinp;
2472         struct usb_device *hubdev;
2473         uint32_t temp;
2474         uint32_t route;
2475         uint32_t rh_port;
2476         uint8_t is_hub;
2477         uint8_t index;
2478         uint8_t depth;
2479
2480         index = udev->controller_slot_id;
2481
2482         DPRINTF("index=%u\n", index);
2483
2484         pcinp = &sc->sc_hw.devs[index].input_pc;
2485
2486         usbd_get_page(pcinp, 0, &buf_inp);
2487
2488         pinp = buf_inp.buffer;
2489
2490         rh_port = 0;
2491         route = 0;
2492
2493         /* figure out route string and root HUB port number */
2494
2495         for (hubdev = udev; hubdev != NULL; hubdev = hubdev->parent_hub) {
2496
2497                 if (hubdev->parent_hub == NULL)
2498                         break;
2499
2500                 depth = hubdev->parent_hub->depth;
2501
2502                 /*
2503                  * NOTE: HS/FS/LS devices and the SS root HUB can have
2504                  * more than 15 ports
2505                  */
2506
2507                 rh_port = hubdev->port_no;
2508
2509                 if (depth == 0)
2510                         break;
2511
2512                 if (rh_port > 15)
2513                         rh_port = 15;
2514
2515                 if (depth < 6)
2516                         route |= rh_port << (4 * (depth - 1));
2517         }
2518
2519         DPRINTF("Route=0x%08x\n", route);
2520
2521         temp = XHCI_SCTX_0_ROUTE_SET(route) |
2522             XHCI_SCTX_0_CTX_NUM_SET(
2523             sc->sc_hw.devs[index].context_num + 1);
2524
2525         switch (udev->speed) {
2526         case USB_SPEED_LOW:
2527                 temp |= XHCI_SCTX_0_SPEED_SET(2);
2528                 if (udev->parent_hs_hub != NULL &&
2529                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2530                     UDPROTO_HSHUBMTT) {
2531                         DPRINTF("Device inherits MTT\n");
2532                         temp |= XHCI_SCTX_0_MTT_SET(1);
2533                 }
2534                 break;
2535         case USB_SPEED_HIGH:
2536                 temp |= XHCI_SCTX_0_SPEED_SET(3);
2537                 if (sc->sc_hw.devs[index].nports != 0 &&
2538                     udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) {
2539                         DPRINTF("HUB supports MTT\n");
2540                         temp |= XHCI_SCTX_0_MTT_SET(1);
2541                 }
2542                 break;
2543         case USB_SPEED_FULL:
2544                 temp |= XHCI_SCTX_0_SPEED_SET(1);
2545                 if (udev->parent_hs_hub != NULL &&
2546                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2547                     UDPROTO_HSHUBMTT) {
2548                         DPRINTF("Device inherits MTT\n");
2549                         temp |= XHCI_SCTX_0_MTT_SET(1);
2550                 }
2551                 break;
2552         default:
2553                 temp |= XHCI_SCTX_0_SPEED_SET(4);
2554                 break;
2555         }
2556
2557         is_hub = sc->sc_hw.devs[index].nports != 0 &&
2558             (udev->speed == USB_SPEED_SUPER ||
2559             udev->speed == USB_SPEED_HIGH);
2560
2561         if (is_hub)
2562                 temp |= XHCI_SCTX_0_HUB_SET(1);
2563
2564         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2565
2566         temp = XHCI_SCTX_1_RH_PORT_SET(rh_port);
2567
2568         if (is_hub) {
2569                 temp |= XHCI_SCTX_1_NUM_PORTS_SET(
2570                     sc->sc_hw.devs[index].nports);
2571         }
2572
2573         switch (udev->speed) {
2574         case USB_SPEED_SUPER:
2575                 switch (sc->sc_hw.devs[index].state) {
2576                 case XHCI_ST_ADDRESSED:
2577                 case XHCI_ST_CONFIGURED:
2578                         /* enable power save */
2579                         temp |= XHCI_SCTX_1_MAX_EL_SET(sc->sc_exit_lat_max);
2580                         break;
2581                 default:
2582                         /* disable power save */
2583                         break;
2584                 }
2585                 break;
2586         default:
2587                 break;
2588         }
2589
2590         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx1, temp);
2591
2592         temp = XHCI_SCTX_2_IRQ_TARGET_SET(0);
2593
2594         if (is_hub) {
2595                 temp |= XHCI_SCTX_2_TT_THINK_TIME_SET(
2596                     sc->sc_hw.devs[index].tt);
2597         }
2598
2599         hubdev = udev->parent_hs_hub;
2600
2601         /* check if we should activate the transaction translator */
2602         switch (udev->speed) {
2603         case USB_SPEED_FULL:
2604         case USB_SPEED_LOW:
2605                 if (hubdev != NULL) {
2606                         temp |= XHCI_SCTX_2_TT_HUB_SID_SET(
2607                             hubdev->controller_slot_id);
2608                         temp |= XHCI_SCTX_2_TT_PORT_NUM_SET(
2609                             udev->hs_port_no);
2610                 }
2611                 break;
2612         default:
2613                 break;
2614         }
2615
2616         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx2, temp);
2617
2618         /*
2619          * These fields should be initialized to zero, according to
2620          * XHCI section 6.2.2 - slot context:
2621          */
2622         temp = XHCI_SCTX_3_DEV_ADDR_SET(0) |
2623             XHCI_SCTX_3_SLOT_STATE_SET(0);
2624
2625         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx3, temp);
2626
2627 #ifdef USB_DEBUG
2628         xhci_dump_device(sc, &pinp->ctx_slot);
2629 #endif
2630         usb_pc_cpu_flush(pcinp);
2631
2632         return (0);             /* success */
2633 }
2634
2635 static usb_error_t
2636 xhci_alloc_device_ext(struct usb_device *udev)
2637 {
2638         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2639         struct usb_page_search buf_dev;
2640         struct usb_page_search buf_ep;
2641         struct xhci_trb *trb;
2642         struct usb_page_cache *pc;
2643         struct usb_page *pg;
2644         uint64_t addr;
2645         uint8_t index;
2646         uint8_t i;
2647
2648         index = udev->controller_slot_id;
2649
2650         pc = &sc->sc_hw.devs[index].device_pc;
2651         pg = &sc->sc_hw.devs[index].device_pg;
2652
2653         /* need to initialize the page cache */
2654         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2655
2656         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2657             (2 * sizeof(struct xhci_dev_ctx)) :
2658             sizeof(struct xhci_dev_ctx), XHCI_PAGE_SIZE))
2659                 goto error;
2660
2661         usbd_get_page(pc, 0, &buf_dev);
2662
2663         pc = &sc->sc_hw.devs[index].input_pc;
2664         pg = &sc->sc_hw.devs[index].input_pg;
2665
2666         /* need to initialize the page cache */
2667         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2668
2669         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2670             (2 * sizeof(struct xhci_input_dev_ctx)) :
2671             sizeof(struct xhci_input_dev_ctx), XHCI_PAGE_SIZE)) {
2672                 goto error;
2673         }
2674
2675         pc = &sc->sc_hw.devs[index].endpoint_pc;
2676         pg = &sc->sc_hw.devs[index].endpoint_pg;
2677
2678         /* need to initialize the page cache */
2679         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2680
2681         if (usb_pc_alloc_mem(pc, pg,
2682             sizeof(struct xhci_dev_endpoint_trbs), XHCI_PAGE_SIZE)) {
2683                 goto error;
2684         }
2685
2686         /* initialise all endpoint LINK TRBs */
2687
2688         for (i = 0; i != XHCI_MAX_ENDPOINTS; i++) {
2689
2690                 /* lookup endpoint TRB ring */
2691                 usbd_get_page(pc, (uintptr_t)&
2692                     ((struct xhci_dev_endpoint_trbs *)0)->trb[i][0], &buf_ep);
2693
2694                 /* get TRB pointer */
2695                 trb = buf_ep.buffer;
2696                 trb += XHCI_MAX_TRANSFERS - 1;
2697
2698                 /* get TRB start address */
2699                 addr = buf_ep.physaddr;
2700
2701                 /* create LINK TRB */
2702                 trb->qwTrb0 = htole64(addr);
2703                 trb->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2704                 trb->dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2705                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2706         }
2707
2708         usb_pc_cpu_flush(pc);
2709
2710         xhci_set_slot_pointer(sc, index, buf_dev.physaddr);
2711
2712         return (0);
2713
2714 error:
2715         xhci_free_device_ext(udev);
2716
2717         return (USB_ERR_NOMEM);
2718 }
2719
2720 static void
2721 xhci_free_device_ext(struct usb_device *udev)
2722 {
2723         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2724         uint8_t index;
2725
2726         index = udev->controller_slot_id;
2727         xhci_set_slot_pointer(sc, index, 0);
2728
2729         usb_pc_free_mem(&sc->sc_hw.devs[index].device_pc);
2730         usb_pc_free_mem(&sc->sc_hw.devs[index].input_pc);
2731         usb_pc_free_mem(&sc->sc_hw.devs[index].endpoint_pc);
2732 }
2733
2734 static struct xhci_endpoint_ext *
2735 xhci_get_endpoint_ext(struct usb_device *udev, struct usb_endpoint_descriptor *edesc)
2736 {
2737         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2738         struct xhci_endpoint_ext *pepext;
2739         struct usb_page_cache *pc;
2740         struct usb_page_search buf_ep;
2741         uint8_t epno;
2742         uint8_t index;
2743
2744         epno = edesc->bEndpointAddress;
2745         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
2746                 epno |= UE_DIR_IN;
2747
2748         epno = XHCI_EPNO2EPID(epno);
2749
2750         index = udev->controller_slot_id;
2751
2752         pc = &sc->sc_hw.devs[index].endpoint_pc;
2753
2754         usbd_get_page(pc, (uintptr_t)&((struct xhci_dev_endpoint_trbs *)0)->trb[epno][0], &buf_ep);
2755
2756         pepext = &sc->sc_hw.devs[index].endp[epno];
2757         pepext->page_cache = pc;
2758         pepext->trb = buf_ep.buffer;
2759         pepext->physaddr = buf_ep.physaddr;
2760
2761         return (pepext);
2762 }
2763
2764 static void
2765 xhci_endpoint_doorbell(struct usb_xfer *xfer)
2766 {
2767         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2768         uint8_t epno;
2769         uint8_t index;
2770
2771         epno = xfer->endpointno;
2772         if (xfer->flags_int.control_xfr)
2773                 epno |= UE_DIR_IN;
2774
2775         epno = XHCI_EPNO2EPID(epno);
2776         index = xfer->xroot->udev->controller_slot_id;
2777
2778         if (xfer->xroot->udev->flags.self_suspended == 0) {
2779                 XWRITE4(sc, door, XHCI_DOORBELL(index),
2780                     epno | XHCI_DB_SID_SET(/*xfer->stream_id*/ 0));
2781         }
2782 }
2783
2784 static void
2785 xhci_transfer_remove(struct usb_xfer *xfer, usb_error_t error)
2786 {
2787         struct xhci_endpoint_ext *pepext;
2788
2789         if (xfer->flags_int.bandwidth_reclaimed) {
2790                 xfer->flags_int.bandwidth_reclaimed = 0;
2791
2792                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2793                     xfer->endpoint->edesc);
2794
2795                 pepext->trb_used--;
2796
2797                 pepext->xfer[xfer->qh_pos] = NULL;
2798
2799                 if (error && pepext->trb_running != 0) {
2800                         pepext->trb_halted = 1;
2801                         pepext->trb_running = 0;
2802                 }
2803         }
2804 }
2805
2806 static usb_error_t
2807 xhci_transfer_insert(struct usb_xfer *xfer)
2808 {
2809         struct xhci_td *td_first;
2810         struct xhci_td *td_last;
2811         struct xhci_trb *trb_link;
2812         struct xhci_endpoint_ext *pepext;
2813         uint64_t addr;
2814         uint8_t i;
2815         uint8_t inext;
2816         uint8_t trb_limit;
2817
2818         DPRINTFN(8, "\n");
2819
2820         /* check if already inserted */
2821         if (xfer->flags_int.bandwidth_reclaimed) {
2822                 DPRINTFN(8, "Already in schedule\n");
2823                 return (0);
2824         }
2825
2826         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2827             xfer->endpoint->edesc);
2828
2829         td_first = xfer->td_transfer_first;
2830         td_last = xfer->td_transfer_last;
2831         addr = pepext->physaddr;
2832
2833         switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2834         case UE_CONTROL:
2835         case UE_INTERRUPT:
2836                 /* single buffered */
2837                 trb_limit = 1;
2838                 break;
2839         default:
2840                 /* multi buffered */
2841                 trb_limit = (XHCI_MAX_TRANSFERS - 2);
2842                 break;
2843         }
2844
2845         if (pepext->trb_used >= trb_limit) {
2846                 DPRINTFN(8, "Too many TDs queued.\n");
2847                 return (USB_ERR_NOMEM);
2848         }
2849
2850         /* check for stopped condition, after putting transfer on interrupt queue */
2851         if (pepext->trb_running == 0) {
2852                 struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2853
2854                 DPRINTFN(8, "Not running\n");
2855
2856                 /* start configuration */
2857                 (void)usb_proc_msignal(&sc->sc_config_proc,
2858                     &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2859                 return (0);
2860         }
2861
2862         pepext->trb_used++;
2863
2864         /* get current TRB index */
2865         i = pepext->trb_index;
2866
2867         /* get next TRB index */
2868         inext = (i + 1);
2869
2870         /* the last entry of the ring is a hardcoded link TRB */
2871         if (inext >= (XHCI_MAX_TRANSFERS - 1))
2872                 inext = 0;
2873
2874         /* compute terminating return address */
2875         addr += inext * sizeof(struct xhci_trb);
2876
2877         /* compute link TRB pointer */
2878         trb_link = td_last->td_trb + td_last->ntrb;
2879
2880         /* update next pointer of last link TRB */
2881         trb_link->qwTrb0 = htole64(addr);
2882         trb_link->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2883         trb_link->dwTrb3 = htole32(XHCI_TRB_3_IOC_BIT |
2884             XHCI_TRB_3_CYCLE_BIT |
2885             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2886
2887 #ifdef USB_DEBUG
2888         xhci_dump_trb(&td_last->td_trb[td_last->ntrb]);
2889 #endif
2890         usb_pc_cpu_flush(td_last->page_cache);
2891
2892         /* write ahead chain end marker */
2893
2894         pepext->trb[inext].qwTrb0 = 0;
2895         pepext->trb[inext].dwTrb2 = 0;
2896         pepext->trb[inext].dwTrb3 = 0;
2897
2898         /* update next pointer of link TRB */
2899
2900         pepext->trb[i].qwTrb0 = htole64((uint64_t)td_first->td_self);
2901         pepext->trb[i].dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2902
2903 #ifdef USB_DEBUG
2904         xhci_dump_trb(&pepext->trb[i]);
2905 #endif
2906         usb_pc_cpu_flush(pepext->page_cache);
2907
2908         /* toggle cycle bit which activates the transfer chain */
2909
2910         pepext->trb[i].dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2911             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2912
2913         usb_pc_cpu_flush(pepext->page_cache);
2914
2915         DPRINTF("qh_pos = %u\n", i);
2916
2917         pepext->xfer[i] = xfer;
2918
2919         xfer->qh_pos = i;
2920
2921         xfer->flags_int.bandwidth_reclaimed = 1;
2922
2923         pepext->trb_index = inext;
2924
2925         xhci_endpoint_doorbell(xfer);
2926
2927         return (0);
2928 }
2929
2930 static void
2931 xhci_root_intr(struct xhci_softc *sc)
2932 {
2933         uint16_t i;
2934
2935         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2936
2937         /* clear any old interrupt data */
2938         memset(sc->sc_hub_idata, 0, sizeof(sc->sc_hub_idata));
2939
2940         for (i = 1; i <= sc->sc_noport; i++) {
2941                 /* pick out CHANGE bits from the status register */
2942                 if (XREAD4(sc, oper, XHCI_PORTSC(i)) & (
2943                     XHCI_PS_CSC | XHCI_PS_PEC |
2944                     XHCI_PS_OCC | XHCI_PS_WRC |
2945                     XHCI_PS_PRC | XHCI_PS_PLC |
2946                     XHCI_PS_CEC)) {
2947                         sc->sc_hub_idata[i / 8] |= 1 << (i % 8);
2948                         DPRINTF("port %d changed\n", i);
2949                 }
2950         }
2951         uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
2952             sizeof(sc->sc_hub_idata));
2953 }
2954
2955 /*------------------------------------------------------------------------*
2956  *      xhci_device_done - XHCI done handler
2957  *
2958  * NOTE: This function can be called two times in a row on
2959  * the same USB transfer. From close and from interrupt.
2960  *------------------------------------------------------------------------*/
2961 static void
2962 xhci_device_done(struct usb_xfer *xfer, usb_error_t error)
2963 {
2964         DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
2965             xfer, xfer->endpoint, error);
2966
2967         /* remove transfer from HW queue */
2968         xhci_transfer_remove(xfer, error);
2969
2970         /* dequeue transfer and start next transfer */
2971         usbd_transfer_done(xfer, error);
2972 }
2973
2974 /*------------------------------------------------------------------------*
2975  * XHCI data transfer support (generic type)
2976  *------------------------------------------------------------------------*/
2977 static void
2978 xhci_device_generic_open(struct usb_xfer *xfer)
2979 {
2980         if (xfer->flags_int.isochronous_xfr) {
2981                 switch (xfer->xroot->udev->speed) {
2982                 case USB_SPEED_FULL:
2983                         break;
2984                 default:
2985                         usb_hs_bandwidth_alloc(xfer);
2986                         break;
2987                 }
2988         }
2989 }
2990
2991 static void
2992 xhci_device_generic_close(struct usb_xfer *xfer)
2993 {
2994         DPRINTF("\n");
2995
2996         xhci_device_done(xfer, USB_ERR_CANCELLED);
2997
2998         if (xfer->flags_int.isochronous_xfr) {
2999                 switch (xfer->xroot->udev->speed) {
3000                 case USB_SPEED_FULL:
3001                         break;
3002                 default:
3003                         usb_hs_bandwidth_free(xfer);
3004                         break;
3005                 }
3006         }
3007 }
3008
3009 static void
3010 xhci_device_generic_multi_enter(struct usb_endpoint *ep,
3011     struct usb_xfer *enter_xfer)
3012 {
3013         struct usb_xfer *xfer;
3014
3015         /* check if there is a current transfer */
3016         xfer = ep->endpoint_q.curr;
3017         if (xfer == NULL)
3018                 return;
3019
3020         /*
3021          * Check if the current transfer is started and then pickup
3022          * the next one, if any. Else wait for next start event due to
3023          * block on failure feature.
3024          */
3025         if (!xfer->flags_int.bandwidth_reclaimed)
3026                 return;
3027
3028         xfer = TAILQ_FIRST(&ep->endpoint_q.head);
3029         if (xfer == NULL) {
3030                 /*
3031                  * In case of enter we have to consider that the
3032                  * transfer is queued by the USB core after the enter
3033                  * method is called.
3034                  */
3035                 xfer = enter_xfer;
3036
3037                 if (xfer == NULL)
3038                         return;
3039         }
3040
3041         /* try to multi buffer */
3042         xhci_transfer_insert(xfer);
3043 }
3044
3045 static void
3046 xhci_device_generic_enter(struct usb_xfer *xfer)
3047 {
3048         DPRINTF("\n");
3049
3050         /* set up TD's and QH */
3051         xhci_setup_generic_chain(xfer);
3052
3053         xhci_device_generic_multi_enter(xfer->endpoint, xfer);
3054 }
3055
3056 static void
3057 xhci_device_generic_start(struct usb_xfer *xfer)
3058 {
3059         DPRINTF("\n");
3060
3061         /* try to insert xfer on HW queue */
3062         xhci_transfer_insert(xfer);
3063
3064         /* try to multi buffer */
3065         xhci_device_generic_multi_enter(xfer->endpoint, NULL);
3066
3067         /* add transfer last on interrupt queue */
3068         usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
3069
3070         /* start timeout, if any */
3071         if (xfer->timeout != 0)
3072                 usbd_transfer_timeout_ms(xfer, &xhci_timeout, xfer->timeout);
3073 }
3074
3075 struct usb_pipe_methods xhci_device_generic_methods =
3076 {
3077         .open = xhci_device_generic_open,
3078         .close = xhci_device_generic_close,
3079         .enter = xhci_device_generic_enter,
3080         .start = xhci_device_generic_start,
3081 };
3082
3083 /*------------------------------------------------------------------------*
3084  * xhci root HUB support
3085  *------------------------------------------------------------------------*
3086  * Simulate a hardware HUB by handling all the necessary requests.
3087  *------------------------------------------------------------------------*/
3088
3089 #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) }
3090
3091 static const
3092 struct usb_device_descriptor xhci_devd =
3093 {
3094         .bLength = sizeof(xhci_devd),
3095         .bDescriptorType = UDESC_DEVICE,        /* type */
3096         HSETW(.bcdUSB, 0x0300),                 /* USB version */
3097         .bDeviceClass = UDCLASS_HUB,            /* class */
3098         .bDeviceSubClass = UDSUBCLASS_HUB,      /* subclass */
3099         .bDeviceProtocol = UDPROTO_SSHUB,       /* protocol */
3100         .bMaxPacketSize = 9,                    /* max packet size */
3101         HSETW(.idVendor, 0x0000),               /* vendor */
3102         HSETW(.idProduct, 0x0000),              /* product */
3103         HSETW(.bcdDevice, 0x0100),              /* device version */
3104         .iManufacturer = 1,
3105         .iProduct = 2,
3106         .iSerialNumber = 0,
3107         .bNumConfigurations = 1,                /* # of configurations */
3108 };
3109
3110 static const
3111 struct xhci_bos_desc xhci_bosd = {
3112         .bosd = {
3113                 .bLength = sizeof(xhci_bosd.bosd),
3114                 .bDescriptorType = UDESC_BOS,
3115                 HSETW(.wTotalLength, sizeof(xhci_bosd)),
3116                 .bNumDeviceCaps = 3,
3117         },
3118         .usb2extd = {
3119                 .bLength = sizeof(xhci_bosd.usb2extd),
3120                 .bDescriptorType = 1,
3121                 .bDevCapabilityType = 2,
3122                 .bmAttributes[0] = 2,
3123         },
3124         .usbdcd = {
3125                 .bLength = sizeof(xhci_bosd.usbdcd),
3126                 .bDescriptorType = UDESC_DEVICE_CAPABILITY,
3127                 .bDevCapabilityType = 3,
3128                 .bmAttributes = 0, /* XXX */
3129                 HSETW(.wSpeedsSupported, 0x000C),
3130                 .bFunctionalitySupport = 8,
3131                 .bU1DevExitLat = 255,   /* dummy - not used */
3132                 .wU2DevExitLat = { 0x00, 0x08 },
3133         },
3134         .cidd = {
3135                 .bLength = sizeof(xhci_bosd.cidd),
3136                 .bDescriptorType = 1,
3137                 .bDevCapabilityType = 4,
3138                 .bReserved = 0,
3139                 .bContainerID = 0, /* XXX */
3140         },
3141 };
3142
3143 static const
3144 struct xhci_config_desc xhci_confd = {
3145         .confd = {
3146                 .bLength = sizeof(xhci_confd.confd),
3147                 .bDescriptorType = UDESC_CONFIG,
3148                 .wTotalLength[0] = sizeof(xhci_confd),
3149                 .bNumInterface = 1,
3150                 .bConfigurationValue = 1,
3151                 .iConfiguration = 0,
3152                 .bmAttributes = UC_SELF_POWERED,
3153                 .bMaxPower = 0          /* max power */
3154         },
3155         .ifcd = {
3156                 .bLength = sizeof(xhci_confd.ifcd),
3157                 .bDescriptorType = UDESC_INTERFACE,
3158                 .bNumEndpoints = 1,
3159                 .bInterfaceClass = UICLASS_HUB,
3160                 .bInterfaceSubClass = UISUBCLASS_HUB,
3161                 .bInterfaceProtocol = 0,
3162         },
3163         .endpd = {
3164                 .bLength = sizeof(xhci_confd.endpd),
3165                 .bDescriptorType = UDESC_ENDPOINT,
3166                 .bEndpointAddress = UE_DIR_IN | XHCI_INTR_ENDPT,
3167                 .bmAttributes = UE_INTERRUPT,
3168                 .wMaxPacketSize[0] = 2,         /* max 15 ports */
3169                 .bInterval = 255,
3170         },
3171         .endpcd = {
3172                 .bLength = sizeof(xhci_confd.endpcd),
3173                 .bDescriptorType = UDESC_ENDPOINT_SS_COMP,
3174                 .bMaxBurst = 0,
3175                 .bmAttributes = 0,
3176         },
3177 };
3178
3179 static const
3180 struct usb_hub_ss_descriptor xhci_hubd = {
3181         .bLength = sizeof(xhci_hubd),
3182         .bDescriptorType = UDESC_SS_HUB,
3183 };
3184
3185 static usb_error_t
3186 xhci_roothub_exec(struct usb_device *udev,
3187     struct usb_device_request *req, const void **pptr, uint16_t *plength)
3188 {
3189         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3190         const char *str_ptr;
3191         const void *ptr;
3192         uint32_t port;
3193         uint32_t v;
3194         uint16_t len;
3195         uint16_t i;
3196         uint16_t value;
3197         uint16_t index;
3198         uint8_t j;
3199         usb_error_t err;
3200
3201         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3202
3203         /* buffer reset */
3204         ptr = (const void *)&sc->sc_hub_desc;
3205         len = 0;
3206         err = 0;
3207
3208         value = UGETW(req->wValue);
3209         index = UGETW(req->wIndex);
3210
3211         DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
3212             "wValue=0x%04x wIndex=0x%04x\n",
3213             req->bmRequestType, req->bRequest,
3214             UGETW(req->wLength), value, index);
3215
3216 #define C(x,y) ((x) | ((y) << 8))
3217         switch (C(req->bRequest, req->bmRequestType)) {
3218         case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
3219         case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
3220         case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
3221                 /*
3222                  * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
3223                  * for the integrated root hub.
3224                  */
3225                 break;
3226         case C(UR_GET_CONFIG, UT_READ_DEVICE):
3227                 len = 1;
3228                 sc->sc_hub_desc.temp[0] = sc->sc_conf;
3229                 break;
3230         case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3231                 switch (value >> 8) {
3232                 case UDESC_DEVICE:
3233                         if ((value & 0xff) != 0) {
3234                                 err = USB_ERR_IOERROR;
3235                                 goto done;
3236                         }
3237                         len = sizeof(xhci_devd);
3238                         ptr = (const void *)&xhci_devd;
3239                         break;
3240
3241                 case UDESC_BOS:
3242                         if ((value & 0xff) != 0) {
3243                                 err = USB_ERR_IOERROR;
3244                                 goto done;
3245                         }
3246                         len = sizeof(xhci_bosd);
3247                         ptr = (const void *)&xhci_bosd;
3248                         break;
3249
3250                 case UDESC_CONFIG:
3251                         if ((value & 0xff) != 0) {
3252                                 err = USB_ERR_IOERROR;
3253                                 goto done;
3254                         }
3255                         len = sizeof(xhci_confd);
3256                         ptr = (const void *)&xhci_confd;
3257                         break;
3258
3259                 case UDESC_STRING:
3260                         switch (value & 0xff) {
3261                         case 0: /* Language table */
3262                                 str_ptr = "\001";
3263                                 break;
3264
3265                         case 1: /* Vendor */
3266                                 str_ptr = sc->sc_vendor;
3267                                 break;
3268
3269                         case 2: /* Product */
3270                                 str_ptr = "XHCI root HUB";
3271                                 break;
3272
3273                         default:
3274                                 str_ptr = "";
3275                                 break;
3276                         }
3277
3278                         len = usb_make_str_desc(
3279                             sc->sc_hub_desc.temp,
3280                             sizeof(sc->sc_hub_desc.temp),
3281                             str_ptr);
3282                         break;
3283
3284                 default:
3285                         err = USB_ERR_IOERROR;
3286                         goto done;
3287                 }
3288                 break;
3289         case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
3290                 len = 1;
3291                 sc->sc_hub_desc.temp[0] = 0;
3292                 break;
3293         case C(UR_GET_STATUS, UT_READ_DEVICE):
3294                 len = 2;
3295                 USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
3296                 break;
3297         case C(UR_GET_STATUS, UT_READ_INTERFACE):
3298         case C(UR_GET_STATUS, UT_READ_ENDPOINT):
3299                 len = 2;
3300                 USETW(sc->sc_hub_desc.stat.wStatus, 0);
3301                 break;
3302         case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
3303                 if (value >= XHCI_MAX_DEVICES) {
3304                         err = USB_ERR_IOERROR;
3305                         goto done;
3306                 }
3307                 break;
3308         case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
3309                 if (value != 0 && value != 1) {
3310                         err = USB_ERR_IOERROR;
3311                         goto done;
3312                 }
3313                 sc->sc_conf = value;
3314                 break;
3315         case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
3316                 break;
3317         case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
3318         case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
3319         case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
3320                 err = USB_ERR_IOERROR;
3321                 goto done;
3322         case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
3323                 break;
3324         case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
3325                 break;
3326                 /* Hub requests */
3327         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3328                 break;
3329         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
3330                 DPRINTFN(9, "UR_CLEAR_PORT_FEATURE\n");
3331
3332                 if ((index < 1) ||
3333                     (index > sc->sc_noport)) {
3334                         err = USB_ERR_IOERROR;
3335                         goto done;
3336                 }
3337                 port = XHCI_PORTSC(index);
3338
3339                 v = XREAD4(sc, oper, port);
3340                 i = XHCI_PS_PLS_GET(v);
3341                 v &= ~XHCI_PS_CLEAR;
3342
3343                 switch (value) {
3344                 case UHF_C_BH_PORT_RESET:
3345                         XWRITE4(sc, oper, port, v | XHCI_PS_WRC);
3346                         break;
3347                 case UHF_C_PORT_CONFIG_ERROR:
3348                         XWRITE4(sc, oper, port, v | XHCI_PS_CEC);
3349                         break;
3350                 case UHF_C_PORT_SUSPEND:
3351                 case UHF_C_PORT_LINK_STATE:
3352                         XWRITE4(sc, oper, port, v | XHCI_PS_PLC);
3353                         break;
3354                 case UHF_C_PORT_CONNECTION:
3355                         XWRITE4(sc, oper, port, v | XHCI_PS_CSC);
3356                         break;
3357                 case UHF_C_PORT_ENABLE:
3358                         XWRITE4(sc, oper, port, v | XHCI_PS_PEC);
3359                         break;
3360                 case UHF_C_PORT_OVER_CURRENT:
3361                         XWRITE4(sc, oper, port, v | XHCI_PS_OCC);
3362                         break;
3363                 case UHF_C_PORT_RESET:
3364                         XWRITE4(sc, oper, port, v | XHCI_PS_PRC);
3365                         break;
3366                 case UHF_PORT_ENABLE:
3367                         XWRITE4(sc, oper, port, v | XHCI_PS_PED);
3368                         break;
3369                 case UHF_PORT_POWER:
3370                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PP);
3371                         break;
3372                 case UHF_PORT_INDICATOR:
3373                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PIC_SET(3));
3374                         break;
3375                 case UHF_PORT_SUSPEND:
3376
3377                         /* U3 -> U15 */
3378                         if (i == 3) {
3379                                 XWRITE4(sc, oper, port, v |
3380                                     XHCI_PS_PLS_SET(0xF) | XHCI_PS_LWS);
3381                         }
3382
3383                         /* wait 20ms for resume sequence to complete */
3384                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
3385
3386                         /* U0 */
3387                         XWRITE4(sc, oper, port, v |
3388                             XHCI_PS_PLS_SET(0) | XHCI_PS_LWS);
3389                         break;
3390                 default:
3391                         err = USB_ERR_IOERROR;
3392                         goto done;
3393                 }
3394                 break;
3395
3396         case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3397                 if ((value & 0xff) != 0) {
3398                         err = USB_ERR_IOERROR;
3399                         goto done;
3400                 }
3401
3402                 v = XREAD4(sc, capa, XHCI_HCSPARAMS0);
3403
3404                 sc->sc_hub_desc.hubd = xhci_hubd;
3405
3406                 sc->sc_hub_desc.hubd.bNbrPorts = sc->sc_noport;
3407
3408                 if (XHCI_HCS0_PPC(v))
3409                         i = UHD_PWR_INDIVIDUAL;
3410                 else
3411                         i = UHD_PWR_GANGED;
3412
3413                 if (XHCI_HCS0_PIND(v))
3414                         i |= UHD_PORT_IND;
3415
3416                 i |= UHD_OC_INDIVIDUAL;
3417
3418                 USETW(sc->sc_hub_desc.hubd.wHubCharacteristics, i);
3419
3420                 /* see XHCI section 5.4.9: */
3421                 sc->sc_hub_desc.hubd.bPwrOn2PwrGood = 10;
3422
3423                 for (j = 1; j <= sc->sc_noport; j++) {
3424
3425                         v = XREAD4(sc, oper, XHCI_PORTSC(j));
3426                         if (v & XHCI_PS_DR) {
3427                                 sc->sc_hub_desc.hubd.
3428                                     DeviceRemovable[j / 8] |= 1U << (j % 8);
3429                         }
3430                 }
3431                 len = sc->sc_hub_desc.hubd.bLength;
3432                 break;
3433
3434         case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3435                 len = 16;
3436                 memset(sc->sc_hub_desc.temp, 0, 16);
3437                 break;
3438
3439         case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
3440                 DPRINTFN(9, "UR_GET_STATUS i=%d\n", index);
3441
3442                 if ((index < 1) ||
3443                     (index > sc->sc_noport)) {
3444                         err = USB_ERR_IOERROR;
3445                         goto done;
3446                 }
3447
3448                 v = XREAD4(sc, oper, XHCI_PORTSC(index));
3449
3450                 DPRINTFN(9, "port status=0x%08x\n", v);
3451
3452                 i = UPS_PORT_LINK_STATE_SET(XHCI_PS_PLS_GET(v));
3453
3454                 switch (XHCI_PS_SPEED_GET(v)) {
3455                 case 3:
3456                         i |= UPS_HIGH_SPEED;
3457                         break;
3458                 case 2:
3459                         i |= UPS_LOW_SPEED;
3460                         break;
3461                 case 1:
3462                         /* FULL speed */
3463                         break;
3464                 default:
3465                         i |= UPS_OTHER_SPEED;
3466                         break;
3467                 }
3468
3469                 if (v & XHCI_PS_CCS)
3470                         i |= UPS_CURRENT_CONNECT_STATUS;
3471                 if (v & XHCI_PS_PED)
3472                         i |= UPS_PORT_ENABLED;
3473                 if (v & XHCI_PS_OCA)
3474                         i |= UPS_OVERCURRENT_INDICATOR;
3475                 if (v & XHCI_PS_PR)
3476                         i |= UPS_RESET;
3477                 if (v & XHCI_PS_PP) {
3478                         /*
3479                          * The USB 3.0 RH is using the
3480                          * USB 2.0's power bit
3481                          */
3482                         i |= UPS_PORT_POWER;
3483                 }
3484                 USETW(sc->sc_hub_desc.ps.wPortStatus, i);
3485
3486                 i = 0;
3487                 if (v & XHCI_PS_CSC)
3488                         i |= UPS_C_CONNECT_STATUS;
3489                 if (v & XHCI_PS_PEC)
3490                         i |= UPS_C_PORT_ENABLED;
3491                 if (v & XHCI_PS_OCC)
3492                         i |= UPS_C_OVERCURRENT_INDICATOR;
3493                 if (v & XHCI_PS_WRC)
3494                         i |= UPS_C_BH_PORT_RESET;
3495                 if (v & XHCI_PS_PRC)
3496                         i |= UPS_C_PORT_RESET;
3497                 if (v & XHCI_PS_PLC)
3498                         i |= UPS_C_PORT_LINK_STATE;
3499                 if (v & XHCI_PS_CEC)
3500                         i |= UPS_C_PORT_CONFIG_ERROR;
3501
3502                 USETW(sc->sc_hub_desc.ps.wPortChange, i);
3503                 len = sizeof(sc->sc_hub_desc.ps);
3504                 break;
3505
3506         case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3507                 err = USB_ERR_IOERROR;
3508                 goto done;
3509
3510         case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3511                 break;
3512
3513         case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
3514
3515                 i = index >> 8;
3516                 index &= 0x00FF;
3517
3518                 if ((index < 1) ||
3519                     (index > sc->sc_noport)) {
3520                         err = USB_ERR_IOERROR;
3521                         goto done;
3522                 }
3523
3524                 port = XHCI_PORTSC(index);
3525                 v = XREAD4(sc, oper, port) & ~XHCI_PS_CLEAR;
3526
3527                 switch (value) {
3528                 case UHF_PORT_U1_TIMEOUT:
3529                         if (XHCI_PS_SPEED_GET(v) != 4) {
3530                                 err = USB_ERR_IOERROR;
3531                                 goto done;
3532                         }
3533                         port = XHCI_PORTPMSC(index);
3534                         v = XREAD4(sc, oper, port);
3535                         v &= ~XHCI_PM3_U1TO_SET(0xFF);
3536                         v |= XHCI_PM3_U1TO_SET(i);
3537                         XWRITE4(sc, oper, port, v);
3538                         break;
3539                 case UHF_PORT_U2_TIMEOUT:
3540                         if (XHCI_PS_SPEED_GET(v) != 4) {
3541                                 err = USB_ERR_IOERROR;
3542                                 goto done;
3543                         }
3544                         port = XHCI_PORTPMSC(index);
3545                         v = XREAD4(sc, oper, port);
3546                         v &= ~XHCI_PM3_U2TO_SET(0xFF);
3547                         v |= XHCI_PM3_U2TO_SET(i);
3548                         XWRITE4(sc, oper, port, v);
3549                         break;
3550                 case UHF_BH_PORT_RESET:
3551                         XWRITE4(sc, oper, port, v | XHCI_PS_WPR);
3552                         break;
3553                 case UHF_PORT_LINK_STATE:
3554                         XWRITE4(sc, oper, port, v |
3555                             XHCI_PS_PLS_SET(i) | XHCI_PS_LWS);
3556                         /* 4ms settle time */
3557                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250);
3558                         break;
3559                 case UHF_PORT_ENABLE:
3560                         DPRINTFN(3, "set port enable %d\n", index);
3561                         break;
3562                 case UHF_PORT_SUSPEND:
3563                         DPRINTFN(6, "suspend port %u (LPM=%u)\n", index, i);
3564                         j = XHCI_PS_SPEED_GET(v);
3565                         if ((j < 1) || (j > 3)) {
3566                                 /* non-supported speed */
3567                                 err = USB_ERR_IOERROR;
3568                                 goto done;
3569                         }
3570                         XWRITE4(sc, oper, port, v |
3571                             XHCI_PS_PLS_SET(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
3572                         break;
3573                 case UHF_PORT_RESET:
3574                         DPRINTFN(6, "reset port %d\n", index);
3575                         XWRITE4(sc, oper, port, v | XHCI_PS_PR);
3576                         break;
3577                 case UHF_PORT_POWER:
3578                         DPRINTFN(3, "set port power %d\n", index);
3579                         XWRITE4(sc, oper, port, v | XHCI_PS_PP);
3580                         break;
3581                 case UHF_PORT_TEST:
3582                         DPRINTFN(3, "set port test %d\n", index);
3583                         break;
3584                 case UHF_PORT_INDICATOR:
3585                         DPRINTFN(3, "set port indicator %d\n", index);
3586
3587                         v &= ~XHCI_PS_PIC_SET(3);
3588                         v |= XHCI_PS_PIC_SET(1);
3589
3590                         XWRITE4(sc, oper, port, v);
3591                         break;
3592                 default:
3593                         err = USB_ERR_IOERROR;
3594                         goto done;
3595                 }
3596                 break;
3597
3598         case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
3599         case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
3600         case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
3601         case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
3602                 break;
3603         default:
3604                 err = USB_ERR_IOERROR;
3605                 goto done;
3606         }
3607 done:
3608         *plength = len;
3609         *pptr = ptr;
3610         return (err);
3611 }
3612
3613 static void
3614 xhci_xfer_setup(struct usb_setup_params *parm)
3615 {
3616         struct usb_page_search page_info;
3617         struct usb_page_cache *pc;
3618         struct xhci_softc *sc;
3619         struct usb_xfer *xfer;
3620         void *last_obj;
3621         uint32_t ntd;
3622         uint32_t n;
3623
3624         sc = XHCI_BUS2SC(parm->udev->bus);
3625         xfer = parm->curr_xfer;
3626
3627         /*
3628          * The proof for the "ntd" formula is illustrated like this:
3629          *
3630          * +------------------------------------+
3631          * |                                    |
3632          * |         |remainder ->              |
3633          * |   +-----+---+                      |
3634          * |   | xxx | x | frm 0                |
3635          * |   +-----+---++                     |
3636          * |   | xxx | xx | frm 1               |
3637          * |   +-----+----+                     |
3638          * |            ...                     |
3639          * +------------------------------------+
3640          *
3641          * "xxx" means a completely full USB transfer descriptor
3642          *
3643          * "x" and "xx" means a short USB packet
3644          *
3645          * For the remainder of an USB transfer modulo
3646          * "max_data_length" we need two USB transfer descriptors.
3647          * One to transfer the remaining data and one to finalise with
3648          * a zero length packet in case the "force_short_xfer" flag is
3649          * set. We only need two USB transfer descriptors in the case
3650          * where the transfer length of the first one is a factor of
3651          * "max_frame_size". The rest of the needed USB transfer
3652          * descriptors is given by the buffer size divided by the
3653          * maximum data payload.
3654          */
3655         parm->hc_max_packet_size = 0x400;
3656         parm->hc_max_packet_count = 16 * 3;
3657         parm->hc_max_frame_size = XHCI_TD_PAYLOAD_MAX;
3658
3659         xfer->flags_int.bdma_enable = 1;
3660
3661         usbd_transfer_setup_sub(parm);
3662
3663         if (xfer->flags_int.isochronous_xfr) {
3664                 ntd = ((1 * xfer->nframes)
3665                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3666         } else if (xfer->flags_int.control_xfr) {
3667                 ntd = ((2 * xfer->nframes) + 1  /* STATUS */
3668                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3669         } else {
3670                 ntd = ((2 * xfer->nframes)
3671                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3672         }
3673
3674 alloc_dma_set:
3675
3676         if (parm->err)
3677                 return;
3678
3679         /*
3680          * Allocate queue heads and transfer descriptors
3681          */
3682         last_obj = NULL;
3683
3684         if (usbd_transfer_setup_sub_malloc(
3685             parm, &pc, sizeof(struct xhci_td),
3686             XHCI_TD_ALIGN, ntd)) {
3687                 parm->err = USB_ERR_NOMEM;
3688                 return;
3689         }
3690         if (parm->buf) {
3691                 for (n = 0; n != ntd; n++) {
3692                         struct xhci_td *td;
3693
3694                         usbd_get_page(pc + n, 0, &page_info);
3695
3696                         td = page_info.buffer;
3697
3698                         /* init TD */
3699                         td->td_self = page_info.physaddr;
3700                         td->obj_next = last_obj;
3701                         td->page_cache = pc + n;
3702
3703                         last_obj = td;
3704
3705                         usb_pc_cpu_flush(pc + n);
3706                 }
3707         }
3708         xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
3709
3710         if (!xfer->flags_int.curr_dma_set) {
3711                 xfer->flags_int.curr_dma_set = 1;
3712                 goto alloc_dma_set;
3713         }
3714 }
3715
3716 static usb_error_t
3717 xhci_configure_reset_endpoint(struct usb_xfer *xfer)
3718 {
3719         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3720         struct usb_page_search buf_inp;
3721         struct usb_device *udev;
3722         struct xhci_endpoint_ext *pepext;
3723         struct usb_endpoint_descriptor *edesc;
3724         struct usb_page_cache *pcinp;
3725         usb_error_t err;
3726         uint8_t index;
3727         uint8_t epno;
3728
3729         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3730             xfer->endpoint->edesc);
3731
3732         udev = xfer->xroot->udev;
3733         index = udev->controller_slot_id;
3734
3735         pcinp = &sc->sc_hw.devs[index].input_pc;
3736
3737         usbd_get_page(pcinp, 0, &buf_inp);
3738
3739         edesc = xfer->endpoint->edesc;
3740
3741         epno = edesc->bEndpointAddress;
3742
3743         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
3744                 epno |= UE_DIR_IN;
3745
3746         epno = XHCI_EPNO2EPID(epno);
3747
3748         if (epno == 0)
3749                 return (USB_ERR_NO_PIPE);               /* invalid */
3750
3751         XHCI_CMD_LOCK(sc);
3752
3753         /* configure endpoint */
3754
3755         err = xhci_configure_endpoint_by_xfer(xfer);
3756
3757         if (err != 0) {
3758                 XHCI_CMD_UNLOCK(sc);
3759                 return (err);
3760         }
3761
3762         /*
3763          * Get the endpoint into the stopped state according to the
3764          * endpoint context state diagram in the XHCI specification:
3765          */
3766
3767         err = xhci_cmd_stop_ep(sc, 0, epno, index);
3768
3769         if (err != 0)
3770                 DPRINTF("Could not stop endpoint %u\n", epno);
3771
3772         err = xhci_cmd_reset_ep(sc, 0, epno, index);
3773
3774         if (err != 0)
3775                 DPRINTF("Could not reset endpoint %u\n", epno);
3776
3777         err = xhci_cmd_set_tr_dequeue_ptr(sc, pepext->physaddr |
3778             XHCI_EPCTX_2_DCS_SET(1), 0, epno, index);
3779
3780         if (err != 0)
3781                 DPRINTF("Could not set dequeue ptr for endpoint %u\n", epno);
3782
3783         /*
3784          * Get the endpoint into the running state according to the
3785          * endpoint context state diagram in the XHCI specification:
3786          */
3787
3788         xhci_configure_mask(udev, (1U << epno) | 1U, 0);
3789
3790         err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
3791
3792         if (err != 0)
3793                 DPRINTF("Could not configure endpoint %u\n", epno);
3794
3795         err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
3796
3797         if (err != 0)
3798                 DPRINTF("Could not configure endpoint %u\n", epno);
3799
3800         XHCI_CMD_UNLOCK(sc);
3801
3802         return (0);
3803 }
3804
3805 static void
3806 xhci_xfer_unsetup(struct usb_xfer *xfer)
3807 {
3808         return;
3809 }
3810
3811 static void
3812 xhci_start_dma_delay(struct usb_xfer *xfer)
3813 {
3814         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3815
3816         /* put transfer on interrupt queue (again) */
3817         usbd_transfer_enqueue(&sc->sc_bus.intr_q, xfer);
3818
3819         (void)usb_proc_msignal(&sc->sc_config_proc,
3820             &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
3821 }
3822
3823 static void
3824 xhci_configure_msg(struct usb_proc_msg *pm)
3825 {
3826         struct xhci_softc *sc;
3827         struct xhci_endpoint_ext *pepext;
3828         struct usb_xfer *xfer;
3829
3830         sc = XHCI_BUS2SC(((struct usb_bus_msg *)pm)->bus);
3831
3832 restart:
3833         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3834
3835                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3836                     xfer->endpoint->edesc);
3837
3838                 if ((pepext->trb_halted != 0) ||
3839                     (pepext->trb_running == 0)) {
3840
3841                         uint8_t i;
3842
3843                         /* clear halted and running */
3844                         pepext->trb_halted = 0;
3845                         pepext->trb_running = 0;
3846
3847                         /* nuke remaining buffered transfers */
3848
3849                         for (i = 0; i != (XHCI_MAX_TRANSFERS - 1); i++) {
3850                                 /*
3851                                  * NOTE: We need to use the timeout
3852                                  * error code here else existing
3853                                  * isochronous clients can get
3854                                  * confused:
3855                                  */
3856                                 if (pepext->xfer[i] != NULL) {
3857                                         xhci_device_done(pepext->xfer[i],
3858                                             USB_ERR_TIMEOUT);
3859                                 }
3860                         }
3861
3862                         /*
3863                          * NOTE: The USB transfer cannot vanish in
3864                          * this state!
3865                          */
3866
3867                         USB_BUS_UNLOCK(&sc->sc_bus);
3868
3869                         xhci_configure_reset_endpoint(xfer);
3870
3871                         USB_BUS_LOCK(&sc->sc_bus);
3872
3873                         /* check if halted is still cleared */
3874                         if (pepext->trb_halted == 0) {
3875                                 pepext->trb_running = 1;
3876                                 pepext->trb_index = 0;
3877                         }
3878                         goto restart;
3879                 }
3880
3881                 if (xfer->flags_int.did_dma_delay) {
3882
3883                         /* remove transfer from interrupt queue (again) */
3884                         usbd_transfer_dequeue(xfer);
3885
3886                         /* we are finally done */
3887                         usb_dma_delay_done_cb(xfer);
3888
3889                         /* queue changed - restart */
3890                         goto restart;
3891                 }
3892         }
3893
3894         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3895
3896                 /* try to insert xfer on HW queue */
3897                 xhci_transfer_insert(xfer);
3898
3899                 /* try to multi buffer */
3900                 xhci_device_generic_multi_enter(xfer->endpoint, NULL);
3901         }
3902 }
3903
3904 static void
3905 xhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
3906     struct usb_endpoint *ep)
3907 {
3908         struct xhci_endpoint_ext *pepext;
3909
3910         DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n",
3911             ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode);
3912
3913         if (udev->parent_hub == NULL) {
3914                 /* root HUB has special endpoint handling */
3915                 return;
3916         }
3917
3918         ep->methods = &xhci_device_generic_methods;
3919
3920         pepext = xhci_get_endpoint_ext(udev, edesc);
3921
3922         USB_BUS_LOCK(udev->bus);
3923         pepext->trb_halted = 1;
3924         pepext->trb_running = 0;
3925         USB_BUS_UNLOCK(udev->bus);
3926 }
3927
3928 static void
3929 xhci_ep_uninit(struct usb_device *udev, struct usb_endpoint *ep)
3930 {
3931
3932 }
3933
3934 static void
3935 xhci_ep_clear_stall(struct usb_device *udev, struct usb_endpoint *ep)
3936 {
3937         struct xhci_endpoint_ext *pepext;
3938
3939         DPRINTF("\n");
3940
3941         if (udev->flags.usb_mode != USB_MODE_HOST) {
3942                 /* not supported */
3943                 return;
3944         }
3945         if (udev->parent_hub == NULL) {
3946                 /* root HUB has special endpoint handling */
3947                 return;
3948         }
3949
3950         pepext = xhci_get_endpoint_ext(udev, ep->edesc);
3951
3952         USB_BUS_LOCK(udev->bus);
3953         pepext->trb_halted = 1;
3954         pepext->trb_running = 0;
3955         USB_BUS_UNLOCK(udev->bus);
3956 }
3957
3958 static usb_error_t
3959 xhci_device_init(struct usb_device *udev)
3960 {
3961         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3962         usb_error_t err;
3963         uint8_t temp;
3964
3965         /* no init for root HUB */
3966         if (udev->parent_hub == NULL)
3967                 return (0);
3968
3969         XHCI_CMD_LOCK(sc);
3970
3971         /* set invalid default */
3972
3973         udev->controller_slot_id = sc->sc_noslot + 1;
3974
3975         /* try to get a new slot ID from the XHCI */
3976
3977         err = xhci_cmd_enable_slot(sc, &temp);
3978
3979         if (err) {
3980                 XHCI_CMD_UNLOCK(sc);
3981                 return (err);
3982         }
3983
3984         if (temp > sc->sc_noslot) {
3985                 XHCI_CMD_UNLOCK(sc);
3986                 return (USB_ERR_BAD_ADDRESS);
3987         }
3988
3989         if (sc->sc_hw.devs[temp].state != XHCI_ST_DISABLED) {
3990                 DPRINTF("slot %u already allocated.\n", temp);
3991                 XHCI_CMD_UNLOCK(sc);
3992                 return (USB_ERR_BAD_ADDRESS);
3993         }
3994
3995         /* store slot ID for later reference */
3996
3997         udev->controller_slot_id = temp;
3998
3999         /* reset data structure */
4000
4001         memset(&sc->sc_hw.devs[temp], 0, sizeof(sc->sc_hw.devs[0]));
4002
4003         /* set mark slot allocated */
4004
4005         sc->sc_hw.devs[temp].state = XHCI_ST_ENABLED;
4006
4007         err = xhci_alloc_device_ext(udev);
4008
4009         XHCI_CMD_UNLOCK(sc);
4010
4011         /* get device into default state */
4012
4013         if (err == 0)
4014                 err = xhci_set_address(udev, NULL, 0);
4015
4016         return (err);
4017 }
4018
4019 static void
4020 xhci_device_uninit(struct usb_device *udev)
4021 {
4022         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4023         uint8_t index;
4024
4025         /* no init for root HUB */
4026         if (udev->parent_hub == NULL)
4027                 return;
4028
4029         XHCI_CMD_LOCK(sc);
4030
4031         index = udev->controller_slot_id;
4032
4033         if (index <= sc->sc_noslot) {
4034                 xhci_cmd_disable_slot(sc, index);
4035                 sc->sc_hw.devs[index].state = XHCI_ST_DISABLED;
4036
4037                 /* free device extension */
4038                 xhci_free_device_ext(udev);
4039         }
4040
4041         XHCI_CMD_UNLOCK(sc);
4042 }
4043
4044 static void
4045 xhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
4046 {
4047         /*
4048          * Wait until the hardware has finished any possible use of
4049          * the transfer descriptor(s)
4050          */
4051         *pus = 2048;                    /* microseconds */
4052 }
4053
4054 static void
4055 xhci_device_resume(struct usb_device *udev)
4056 {
4057         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4058         uint8_t index;
4059         uint8_t n;
4060         uint8_t p;
4061
4062         DPRINTF("\n");
4063
4064         /* check for root HUB */
4065         if (udev->parent_hub == NULL)
4066                 return;
4067
4068         index = udev->controller_slot_id;
4069
4070         XHCI_CMD_LOCK(sc);
4071
4072         /* blindly resume all endpoints */
4073
4074         USB_BUS_LOCK(udev->bus);
4075
4076         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4077                 for (p = 0; p != 1 /*XHCI_MAX_STREAMS*/; p++) {
4078                         XWRITE4(sc, door, XHCI_DOORBELL(index),
4079                             n | XHCI_DB_SID_SET(p));
4080                 }
4081         }
4082
4083         USB_BUS_UNLOCK(udev->bus);
4084
4085         XHCI_CMD_UNLOCK(sc);
4086 }
4087
4088 static void
4089 xhci_device_suspend(struct usb_device *udev)
4090 {
4091         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4092         uint8_t index;
4093         uint8_t n;
4094         usb_error_t err;
4095
4096         DPRINTF("\n");
4097
4098         /* check for root HUB */
4099         if (udev->parent_hub == NULL)
4100                 return;
4101
4102         index = udev->controller_slot_id;
4103
4104         XHCI_CMD_LOCK(sc);
4105
4106         /* blindly suspend all endpoints */
4107
4108         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4109                 err = xhci_cmd_stop_ep(sc, 1, n, index);
4110                 if (err != 0) {
4111                         DPRINTF("Failed to suspend endpoint "
4112                             "%u on slot %u (ignored).\n", n, index);
4113                 }
4114         }
4115
4116         XHCI_CMD_UNLOCK(sc);
4117 }
4118
4119 static void
4120 xhci_set_hw_power(struct usb_bus *bus)
4121 {
4122         DPRINTF("\n");
4123 }
4124
4125 static void
4126 xhci_device_state_change(struct usb_device *udev)
4127 {
4128         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4129         struct usb_page_search buf_inp;
4130         usb_error_t err;
4131         uint8_t index;
4132
4133         /* check for root HUB */
4134         if (udev->parent_hub == NULL)
4135                 return;
4136
4137         index = udev->controller_slot_id;
4138
4139         DPRINTF("\n");
4140
4141         if (usb_get_device_state(udev) == USB_STATE_CONFIGURED) {
4142                 err = uhub_query_info(udev, &sc->sc_hw.devs[index].nports, 
4143                     &sc->sc_hw.devs[index].tt);
4144                 if (err != 0)
4145                         sc->sc_hw.devs[index].nports = 0;
4146         }
4147
4148         XHCI_CMD_LOCK(sc);
4149
4150         switch (usb_get_device_state(udev)) {
4151         case USB_STATE_POWERED:
4152                 if (sc->sc_hw.devs[index].state == XHCI_ST_DEFAULT)
4153                         break;
4154
4155                 /* set default state */
4156                 sc->sc_hw.devs[index].state = XHCI_ST_DEFAULT;
4157
4158                 /* reset number of contexts */
4159                 sc->sc_hw.devs[index].context_num = 0;
4160
4161                 err = xhci_cmd_reset_dev(sc, index);
4162
4163                 if (err != 0) {
4164                         DPRINTF("Device reset failed "
4165                             "for slot %u.\n", index);
4166                 }
4167                 break;
4168
4169         case USB_STATE_ADDRESSED:
4170                 if (sc->sc_hw.devs[index].state == XHCI_ST_ADDRESSED)
4171                         break;
4172
4173                 sc->sc_hw.devs[index].state = XHCI_ST_ADDRESSED;
4174
4175                 err = xhci_cmd_configure_ep(sc, 0, 1, index);
4176
4177                 if (err) {
4178                         DPRINTF("Failed to deconfigure "
4179                             "slot %u.\n", index);
4180                 }
4181                 break;
4182
4183         case USB_STATE_CONFIGURED:
4184                 if (sc->sc_hw.devs[index].state == XHCI_ST_CONFIGURED)
4185                         break;
4186
4187                 /* set configured state */
4188                 sc->sc_hw.devs[index].state = XHCI_ST_CONFIGURED;
4189
4190                 /* reset number of contexts */
4191                 sc->sc_hw.devs[index].context_num = 0;
4192
4193                 usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
4194
4195                 xhci_configure_mask(udev, 3, 0);
4196
4197                 err = xhci_configure_device(udev);
4198                 if (err != 0) {
4199                         DPRINTF("Could not configure device "
4200                             "at slot %u.\n", index);
4201                 }
4202
4203                 err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
4204                 if (err != 0) {
4205                         DPRINTF("Could not evaluate device "
4206                             "context at slot %u.\n", index);
4207                 }
4208                 break;
4209
4210         default:
4211                 break;
4212         }
4213         XHCI_CMD_UNLOCK(sc);
4214 }
4215
4216 struct usb_bus_methods xhci_bus_methods = {
4217         .endpoint_init = xhci_ep_init,
4218         .endpoint_uninit = xhci_ep_uninit,
4219         .xfer_setup = xhci_xfer_setup,
4220         .xfer_unsetup = xhci_xfer_unsetup,
4221         .get_dma_delay = xhci_get_dma_delay,
4222         .device_init = xhci_device_init,
4223         .device_uninit = xhci_device_uninit,
4224         .device_resume = xhci_device_resume,
4225         .device_suspend = xhci_device_suspend,
4226         .set_hw_power = xhci_set_hw_power,
4227         .roothub_exec = xhci_roothub_exec,
4228         .xfer_poll = xhci_do_poll,
4229         .start_dma_delay = xhci_start_dma_delay,
4230         .set_address = xhci_set_address,
4231         .clear_stall = xhci_ep_clear_stall,
4232         .device_state_change = xhci_device_state_change,
4233         .set_hw_power_sleep = xhci_set_hw_power_sleep,
4234 };