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