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