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