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