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