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