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