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