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