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