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