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