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