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