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