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