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