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