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