]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/usb/controller/xhci.c
MFC r256750:
[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
1114                 /*
1115                  * Try to abort the last command as per section
1116                  * 4.6.1.2 "Aborting a Command" of the XHCI
1117                  * specification:
1118                  */
1119                 temp = XREAD4(sc, oper, XHCI_CRCR_LO);
1120                 XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CA);
1121
1122                 /* wait for abort event, if any */
1123                 err = cv_timedwait(&sc->sc_cmd_cv, &sc->sc_bus.bus_mtx, hz / 16);
1124
1125                 if (err != 0 && xhci_interrupt_poll(sc) != 0) {
1126                         DPRINTF("Command was completed when polling\n");
1127                         err = 0;
1128                 }
1129                 if (err != 0) {
1130                         DPRINTF("Command abort timeout!\n");
1131                 }
1132                 err = USB_ERR_TIMEOUT;
1133                 trb->dwTrb2 = 0;
1134                 trb->dwTrb3 = 0;
1135         } else {
1136                 temp = le32toh(sc->sc_cmd_result[0]);
1137                 if (XHCI_TRB_2_ERROR_GET(temp) != XHCI_TRB_ERROR_SUCCESS)
1138                         err = USB_ERR_IOERROR;
1139
1140                 trb->dwTrb2 = sc->sc_cmd_result[0];
1141                 trb->dwTrb3 = sc->sc_cmd_result[1];
1142         }
1143
1144         USB_BUS_UNLOCK(&sc->sc_bus);
1145
1146         return (err);
1147 }
1148
1149 #if 0
1150 static usb_error_t
1151 xhci_cmd_nop(struct xhci_softc *sc)
1152 {
1153         struct xhci_trb trb;
1154         uint32_t temp;
1155
1156         DPRINTF("\n");
1157
1158         trb.qwTrb0 = 0;
1159         trb.dwTrb2 = 0;
1160         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NOOP);
1161
1162         trb.dwTrb3 = htole32(temp);
1163
1164         return (xhci_do_command(sc, &trb, 100 /* ms */));
1165 }
1166 #endif
1167
1168 static usb_error_t
1169 xhci_cmd_enable_slot(struct xhci_softc *sc, uint8_t *pslot)
1170 {
1171         struct xhci_trb trb;
1172         uint32_t temp;
1173         usb_error_t err;
1174
1175         DPRINTF("\n");
1176
1177         trb.qwTrb0 = 0;
1178         trb.dwTrb2 = 0;
1179         trb.dwTrb3 = htole32(XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT));
1180
1181         err = xhci_do_command(sc, &trb, 100 /* ms */);
1182         if (err)
1183                 goto done;
1184
1185         temp = le32toh(trb.dwTrb3);
1186
1187         *pslot = XHCI_TRB_3_SLOT_GET(temp); 
1188
1189 done:
1190         return (err);
1191 }
1192
1193 static usb_error_t
1194 xhci_cmd_disable_slot(struct xhci_softc *sc, uint8_t slot_id)
1195 {
1196         struct xhci_trb trb;
1197         uint32_t temp;
1198
1199         DPRINTF("\n");
1200
1201         trb.qwTrb0 = 0;
1202         trb.dwTrb2 = 0;
1203         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT) |
1204             XHCI_TRB_3_SLOT_SET(slot_id);
1205
1206         trb.dwTrb3 = htole32(temp);
1207
1208         return (xhci_do_command(sc, &trb, 100 /* ms */));
1209 }
1210
1211 static usb_error_t
1212 xhci_cmd_set_address(struct xhci_softc *sc, uint64_t input_ctx,
1213     uint8_t bsr, uint8_t slot_id)
1214 {
1215         struct xhci_trb trb;
1216         uint32_t temp;
1217
1218         DPRINTF("\n");
1219
1220         trb.qwTrb0 = htole64(input_ctx);
1221         trb.dwTrb2 = 0;
1222         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
1223             XHCI_TRB_3_SLOT_SET(slot_id);
1224
1225         if (bsr)
1226                 temp |= XHCI_TRB_3_BSR_BIT;
1227
1228         trb.dwTrb3 = htole32(temp);
1229
1230         return (xhci_do_command(sc, &trb, 500 /* ms */));
1231 }
1232
1233 static usb_error_t
1234 xhci_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t address)
1235 {
1236         struct usb_page_search buf_inp;
1237         struct usb_page_search buf_dev;
1238         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
1239         struct xhci_hw_dev *hdev;
1240         struct xhci_dev_ctx *pdev;
1241         struct xhci_endpoint_ext *pepext;
1242         uint32_t temp;
1243         uint16_t mps;
1244         usb_error_t err;
1245         uint8_t index;
1246
1247         /* the root HUB case is not handled here */
1248         if (udev->parent_hub == NULL)
1249                 return (USB_ERR_INVAL);
1250
1251         index = udev->controller_slot_id;
1252
1253         hdev =  &sc->sc_hw.devs[index];
1254
1255         if (mtx != NULL)
1256                 mtx_unlock(mtx);
1257
1258         XHCI_CMD_LOCK(sc);
1259
1260         switch (hdev->state) {
1261         case XHCI_ST_DEFAULT:
1262         case XHCI_ST_ENABLED:
1263
1264                 hdev->state = XHCI_ST_ENABLED;
1265
1266                 /* set configure mask to slot and EP0 */
1267                 xhci_configure_mask(udev, 3, 0);
1268
1269                 /* configure input slot context structure */
1270                 err = xhci_configure_device(udev);
1271
1272                 if (err != 0) {
1273                         DPRINTF("Could not configure device\n");
1274                         break;
1275                 }
1276
1277                 /* configure input endpoint context structure */
1278                 switch (udev->speed) {
1279                 case USB_SPEED_LOW:
1280                 case USB_SPEED_FULL:
1281                         mps = 8;
1282                         break;
1283                 case USB_SPEED_HIGH:
1284                         mps = 64;
1285                         break;
1286                 default:
1287                         mps = 512;
1288                         break;
1289                 }
1290
1291                 pepext = xhci_get_endpoint_ext(udev,
1292                     &udev->ctrl_ep_desc);
1293                 err = xhci_configure_endpoint(udev,
1294                     &udev->ctrl_ep_desc, pepext->physaddr,
1295                     0, 1, 1, 0, mps, mps);
1296
1297                 if (err != 0) {
1298                         DPRINTF("Could not configure default endpoint\n");
1299                         break;
1300                 }
1301
1302                 /* execute set address command */
1303                 usbd_get_page(&hdev->input_pc, 0, &buf_inp);
1304
1305                 err = xhci_cmd_set_address(sc, buf_inp.physaddr,
1306                     (address == 0), index);
1307
1308                 if (err != 0) {
1309                         temp = le32toh(sc->sc_cmd_result[0]);
1310                         if (address == 0 && sc->sc_port_route != NULL &&
1311                             XHCI_TRB_2_ERROR_GET(temp) ==
1312                             XHCI_TRB_ERROR_PARAMETER) {
1313                                 /* LynxPoint XHCI - ports are not switchable */
1314                                 /* Un-route all ports from the XHCI */
1315                                 sc->sc_port_route(sc->sc_bus.parent, 0, ~0);
1316                         }
1317                         DPRINTF("Could not set address "
1318                             "for slot %u.\n", index);
1319                         if (address != 0)
1320                                 break;
1321                 }
1322
1323                 /* update device address to new value */
1324
1325                 usbd_get_page(&hdev->device_pc, 0, &buf_dev);
1326                 pdev = buf_dev.buffer;
1327                 usb_pc_cpu_invalidate(&hdev->device_pc);
1328
1329                 temp = xhci_ctx_get_le32(sc, &pdev->ctx_slot.dwSctx3);
1330                 udev->address = XHCI_SCTX_3_DEV_ADDR_GET(temp);
1331
1332                 /* update device state to new value */
1333
1334                 if (address != 0)
1335                         hdev->state = XHCI_ST_ADDRESSED;
1336                 else
1337                         hdev->state = XHCI_ST_DEFAULT;
1338                 break;
1339
1340         default:
1341                 DPRINTF("Wrong state for set address.\n");
1342                 err = USB_ERR_IOERROR;
1343                 break;
1344         }
1345         XHCI_CMD_UNLOCK(sc);
1346
1347         if (mtx != NULL)
1348                 mtx_lock(mtx);
1349
1350         return (err);
1351 }
1352
1353 static usb_error_t
1354 xhci_cmd_configure_ep(struct xhci_softc *sc, uint64_t input_ctx,
1355     uint8_t deconfigure, uint8_t slot_id)
1356 {
1357         struct xhci_trb trb;
1358         uint32_t temp;
1359
1360         DPRINTF("\n");
1361
1362         trb.qwTrb0 = htole64(input_ctx);
1363         trb.dwTrb2 = 0;
1364         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP) |
1365             XHCI_TRB_3_SLOT_SET(slot_id);
1366
1367         if (deconfigure)
1368                 temp |= XHCI_TRB_3_DCEP_BIT;
1369
1370         trb.dwTrb3 = htole32(temp);
1371
1372         return (xhci_do_command(sc, &trb, 100 /* ms */));
1373 }
1374
1375 static usb_error_t
1376 xhci_cmd_evaluate_ctx(struct xhci_softc *sc, uint64_t input_ctx,
1377     uint8_t slot_id)
1378 {
1379         struct xhci_trb trb;
1380         uint32_t temp;
1381
1382         DPRINTF("\n");
1383
1384         trb.qwTrb0 = htole64(input_ctx);
1385         trb.dwTrb2 = 0;
1386         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX) |
1387             XHCI_TRB_3_SLOT_SET(slot_id);
1388         trb.dwTrb3 = htole32(temp);
1389
1390         return (xhci_do_command(sc, &trb, 100 /* ms */));
1391 }
1392
1393 static usb_error_t
1394 xhci_cmd_reset_ep(struct xhci_softc *sc, uint8_t preserve,
1395     uint8_t ep_id, uint8_t slot_id)
1396 {
1397         struct xhci_trb trb;
1398         uint32_t temp;
1399
1400         DPRINTF("\n");
1401
1402         trb.qwTrb0 = 0;
1403         trb.dwTrb2 = 0;
1404         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP) |
1405             XHCI_TRB_3_SLOT_SET(slot_id) |
1406             XHCI_TRB_3_EP_SET(ep_id);
1407
1408         if (preserve)
1409                 temp |= XHCI_TRB_3_PRSV_BIT;
1410
1411         trb.dwTrb3 = htole32(temp);
1412
1413         return (xhci_do_command(sc, &trb, 100 /* ms */));
1414 }
1415
1416 static usb_error_t
1417 xhci_cmd_set_tr_dequeue_ptr(struct xhci_softc *sc, uint64_t dequeue_ptr,
1418     uint16_t stream_id, uint8_t ep_id, uint8_t slot_id)
1419 {
1420         struct xhci_trb trb;
1421         uint32_t temp;
1422
1423         DPRINTF("\n");
1424
1425         trb.qwTrb0 = htole64(dequeue_ptr);
1426
1427         temp = XHCI_TRB_2_STREAM_SET(stream_id);
1428         trb.dwTrb2 = htole32(temp);
1429
1430         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE) |
1431             XHCI_TRB_3_SLOT_SET(slot_id) |
1432             XHCI_TRB_3_EP_SET(ep_id);
1433         trb.dwTrb3 = htole32(temp);
1434
1435         return (xhci_do_command(sc, &trb, 100 /* ms */));
1436 }
1437
1438 static usb_error_t
1439 xhci_cmd_stop_ep(struct xhci_softc *sc, uint8_t suspend,
1440     uint8_t ep_id, uint8_t slot_id)
1441 {
1442         struct xhci_trb trb;
1443         uint32_t temp;
1444
1445         DPRINTF("\n");
1446
1447         trb.qwTrb0 = 0;
1448         trb.dwTrb2 = 0;
1449         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP) |
1450             XHCI_TRB_3_SLOT_SET(slot_id) |
1451             XHCI_TRB_3_EP_SET(ep_id);
1452
1453         if (suspend)
1454                 temp |= XHCI_TRB_3_SUSP_EP_BIT;
1455
1456         trb.dwTrb3 = htole32(temp);
1457
1458         return (xhci_do_command(sc, &trb, 100 /* ms */));
1459 }
1460
1461 static usb_error_t
1462 xhci_cmd_reset_dev(struct xhci_softc *sc, uint8_t slot_id)
1463 {
1464         struct xhci_trb trb;
1465         uint32_t temp;
1466
1467         DPRINTF("\n");
1468
1469         trb.qwTrb0 = 0;
1470         trb.dwTrb2 = 0;
1471         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_DEVICE) |
1472             XHCI_TRB_3_SLOT_SET(slot_id);
1473
1474         trb.dwTrb3 = htole32(temp);
1475
1476         return (xhci_do_command(sc, &trb, 100 /* ms */));
1477 }
1478
1479 /*------------------------------------------------------------------------*
1480  *      xhci_interrupt - XHCI interrupt handler
1481  *------------------------------------------------------------------------*/
1482 void
1483 xhci_interrupt(struct xhci_softc *sc)
1484 {
1485         uint32_t status;
1486
1487         USB_BUS_LOCK(&sc->sc_bus);
1488
1489         status = XREAD4(sc, oper, XHCI_USBSTS);
1490         if (status == 0)
1491                 goto done;
1492
1493         /* acknowledge interrupts */
1494
1495         XWRITE4(sc, oper, XHCI_USBSTS, status);
1496
1497         DPRINTFN(16, "real interrupt (status=0x%08x)\n", status);
1498  
1499         if (status & XHCI_STS_EINT) {
1500                 /* check for event(s) */
1501                 xhci_interrupt_poll(sc);
1502         }
1503
1504         if (status & (XHCI_STS_PCD | XHCI_STS_HCH |
1505             XHCI_STS_HSE | XHCI_STS_HCE)) {
1506
1507                 if (status & XHCI_STS_PCD) {
1508                         xhci_root_intr(sc);
1509                 }
1510
1511                 if (status & XHCI_STS_HCH) {
1512                         printf("%s: host controller halted\n",
1513                             __FUNCTION__);
1514                 }
1515
1516                 if (status & XHCI_STS_HSE) {
1517                         printf("%s: host system error\n",
1518                             __FUNCTION__);
1519                 }
1520
1521                 if (status & XHCI_STS_HCE) {
1522                         printf("%s: host controller error\n",
1523                            __FUNCTION__);
1524                 }
1525         }
1526 done:
1527         USB_BUS_UNLOCK(&sc->sc_bus);
1528 }
1529
1530 /*------------------------------------------------------------------------*
1531  *      xhci_timeout - XHCI timeout handler
1532  *------------------------------------------------------------------------*/
1533 static void
1534 xhci_timeout(void *arg)
1535 {
1536         struct usb_xfer *xfer = arg;
1537
1538         DPRINTF("xfer=%p\n", xfer);
1539
1540         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1541
1542         /* transfer is transferred */
1543         xhci_device_done(xfer, USB_ERR_TIMEOUT);
1544 }
1545
1546 static void
1547 xhci_do_poll(struct usb_bus *bus)
1548 {
1549         struct xhci_softc *sc = XHCI_BUS2SC(bus);
1550
1551         USB_BUS_LOCK(&sc->sc_bus);
1552         xhci_interrupt_poll(sc);
1553         USB_BUS_UNLOCK(&sc->sc_bus);
1554 }
1555
1556 static void
1557 xhci_setup_generic_chain_sub(struct xhci_std_temp *temp)
1558 {
1559         struct usb_page_search buf_res;
1560         struct xhci_td *td;
1561         struct xhci_td *td_next;
1562         struct xhci_td *td_alt_next;
1563         struct xhci_td *td_first;
1564         uint32_t buf_offset;
1565         uint32_t average;
1566         uint32_t len_old;
1567         uint32_t npkt_off;
1568         uint32_t dword;
1569         uint8_t shortpkt_old;
1570         uint8_t precompute;
1571         uint8_t x;
1572
1573         td_alt_next = NULL;
1574         buf_offset = 0;
1575         shortpkt_old = temp->shortpkt;
1576         len_old = temp->len;
1577         npkt_off = 0;
1578         precompute = 1;
1579
1580 restart:
1581
1582         td = temp->td;
1583         td_next = td_first = temp->td_next;
1584
1585         while (1) {
1586
1587                 if (temp->len == 0) {
1588
1589                         if (temp->shortpkt)
1590                                 break;
1591
1592                         /* send a Zero Length Packet, ZLP, last */
1593
1594                         temp->shortpkt = 1;
1595                         average = 0;
1596
1597                 } else {
1598
1599                         average = temp->average;
1600
1601                         if (temp->len < average) {
1602                                 if (temp->len % temp->max_packet_size) {
1603                                         temp->shortpkt = 1;
1604                                 }
1605                                 average = temp->len;
1606                         }
1607                 }
1608
1609                 if (td_next == NULL)
1610                         panic("%s: out of XHCI transfer descriptors!", __FUNCTION__);
1611
1612                 /* get next TD */
1613
1614                 td = td_next;
1615                 td_next = td->obj_next;
1616
1617                 /* check if we are pre-computing */
1618
1619                 if (precompute) {
1620
1621                         /* update remaining length */
1622
1623                         temp->len -= average;
1624
1625                         continue;
1626                 }
1627                 /* fill out current TD */
1628
1629                 td->len = average;
1630                 td->remainder = 0;
1631                 td->status = 0;
1632
1633                 /* update remaining length */
1634
1635                 temp->len -= average;
1636
1637                 /* reset TRB index */
1638
1639                 x = 0;
1640
1641                 if (temp->trb_type == XHCI_TRB_TYPE_SETUP_STAGE) {
1642                         /* immediate data */
1643
1644                         if (average > 8)
1645                                 average = 8;
1646
1647                         td->td_trb[0].qwTrb0 = 0;
1648
1649                         usbd_copy_out(temp->pc, temp->offset + buf_offset, 
1650                            (uint8_t *)(uintptr_t)&td->td_trb[0].qwTrb0,
1651                            average);
1652
1653                         dword = XHCI_TRB_2_BYTES_SET(8) |
1654                             XHCI_TRB_2_TDSZ_SET(0) |
1655                             XHCI_TRB_2_IRQ_SET(0);
1656
1657                         td->td_trb[0].dwTrb2 = htole32(dword);
1658
1659                         dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
1660                           XHCI_TRB_3_IDT_BIT | XHCI_TRB_3_CYCLE_BIT;
1661
1662                         /* check wLength */
1663                         if (td->td_trb[0].qwTrb0 &
1664                            htole64(XHCI_TRB_0_WLENGTH_MASK)) {
1665                                 if (td->td_trb[0].qwTrb0 & htole64(1))
1666                                         dword |= XHCI_TRB_3_TRT_IN;
1667                                 else
1668                                         dword |= XHCI_TRB_3_TRT_OUT;
1669                         }
1670
1671                         td->td_trb[0].dwTrb3 = htole32(dword);
1672 #ifdef USB_DEBUG
1673                         xhci_dump_trb(&td->td_trb[x]);
1674 #endif
1675                         x++;
1676
1677                 } else do {
1678
1679                         uint32_t npkt;
1680
1681                         /* fill out buffer pointers */
1682
1683                         if (average == 0) {
1684                                 memset(&buf_res, 0, sizeof(buf_res));
1685                         } else {
1686                                 usbd_get_page(temp->pc, temp->offset +
1687                                     buf_offset, &buf_res);
1688
1689                                 /* get length to end of page */
1690                                 if (buf_res.length > average)
1691                                         buf_res.length = average;
1692
1693                                 /* check for maximum length */
1694                                 if (buf_res.length > XHCI_TD_PAGE_SIZE)
1695                                         buf_res.length = XHCI_TD_PAGE_SIZE;
1696
1697                                 npkt_off += buf_res.length;
1698                         }
1699
1700                         /* setup npkt */
1701                         npkt = (len_old - npkt_off + temp->max_packet_size - 1) /
1702                             temp->max_packet_size;
1703
1704                         if (npkt == 0)
1705                                 npkt = 1;
1706                         else if (npkt > 31)
1707                                 npkt = 31;
1708
1709                         /* fill out TRB's */
1710                         td->td_trb[x].qwTrb0 =
1711                             htole64((uint64_t)buf_res.physaddr);
1712
1713                         dword =
1714                           XHCI_TRB_2_BYTES_SET(buf_res.length) |
1715                           XHCI_TRB_2_TDSZ_SET(npkt) | 
1716                           XHCI_TRB_2_IRQ_SET(0);
1717
1718                         td->td_trb[x].dwTrb2 = htole32(dword);
1719
1720                         switch (temp->trb_type) {
1721                         case XHCI_TRB_TYPE_ISOCH:
1722                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1723                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
1724                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1725                                 if (td != td_first) {
1726                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
1727                                 } else if (temp->do_isoc_sync != 0) {
1728                                         temp->do_isoc_sync = 0;
1729                                         /* wait until "isoc_frame" */
1730                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1731                                             XHCI_TRB_3_FRID_SET(temp->isoc_frame / 8);
1732                                 } else {
1733                                         /* start data transfer at next interval */
1734                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1735                                             XHCI_TRB_3_ISO_SIA_BIT;
1736                                 }
1737                                 if (temp->direction == UE_DIR_IN)
1738                                         dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
1739                                 break;
1740                         case XHCI_TRB_TYPE_DATA_STAGE:
1741                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1742                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE) |
1743                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
1744                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1745                                 if (temp->direction == UE_DIR_IN)
1746                                         dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
1747                                 break;
1748                         case XHCI_TRB_TYPE_STATUS_STAGE:
1749                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1750                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE) |
1751                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
1752                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1753                                 if (temp->direction == UE_DIR_IN)
1754                                         dword |= XHCI_TRB_3_DIR_IN;
1755                                 break;
1756                         default:        /* XHCI_TRB_TYPE_NORMAL */
1757                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1758                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL) |
1759                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
1760                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1761                                 if (temp->direction == UE_DIR_IN)
1762                                         dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
1763                                 break;
1764                         }
1765                         td->td_trb[x].dwTrb3 = htole32(dword);
1766
1767                         average -= buf_res.length;
1768                         buf_offset += buf_res.length;
1769 #ifdef USB_DEBUG
1770                         xhci_dump_trb(&td->td_trb[x]);
1771 #endif
1772                         x++;
1773
1774                 } while (average != 0);
1775
1776                 td->td_trb[x-1].dwTrb3 |= htole32(XHCI_TRB_3_IOC_BIT);
1777
1778                 /* store number of data TRB's */
1779
1780                 td->ntrb = x;
1781
1782                 DPRINTF("NTRB=%u\n", x);
1783
1784                 /* fill out link TRB */
1785
1786                 if (td_next != NULL) {
1787                         /* link the current TD with the next one */
1788                         td->td_trb[x].qwTrb0 = htole64((uint64_t)td_next->td_self);
1789                         DPRINTF("LINK=0x%08llx\n", (long long)td_next->td_self);
1790                 } else {
1791                         /* this field will get updated later */
1792                         DPRINTF("NOLINK\n");
1793                 }
1794
1795                 dword = XHCI_TRB_2_IRQ_SET(0);
1796
1797                 td->td_trb[x].dwTrb2 = htole32(dword);
1798
1799                 dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
1800                     XHCI_TRB_3_CYCLE_BIT | XHCI_TRB_3_IOC_BIT;
1801
1802                 td->td_trb[x].dwTrb3 = htole32(dword);
1803
1804                 td->alt_next = td_alt_next;
1805 #ifdef USB_DEBUG
1806                 xhci_dump_trb(&td->td_trb[x]);
1807 #endif
1808                 usb_pc_cpu_flush(td->page_cache);
1809         }
1810
1811         if (precompute) {
1812                 precompute = 0;
1813
1814                 /* setup alt next pointer, if any */
1815                 if (temp->last_frame) {
1816                         td_alt_next = NULL;
1817                 } else {
1818                         /* we use this field internally */
1819                         td_alt_next = td_next;
1820                 }
1821
1822                 /* restore */
1823                 temp->shortpkt = shortpkt_old;
1824                 temp->len = len_old;
1825                 goto restart;
1826         }
1827
1828         /*
1829          * Remove cycle bit from the first TRB if we are
1830          * stepping them:
1831          */
1832         if (temp->step_td != 0) {
1833                 td_first->td_trb[0].dwTrb3 &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
1834                 usb_pc_cpu_flush(td_first->page_cache);
1835         }
1836
1837         /* clear TD SIZE to zero, hence this is the last TRB */
1838         /* remove chain bit because this is the last TRB in the chain */
1839         td->td_trb[td->ntrb - 1].dwTrb2 &= ~htole32(XHCI_TRB_2_TDSZ_SET(15));
1840         td->td_trb[td->ntrb - 1].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
1841
1842         usb_pc_cpu_flush(td->page_cache);
1843
1844         temp->td = td;
1845         temp->td_next = td_next;
1846 }
1847
1848 static void
1849 xhci_setup_generic_chain(struct usb_xfer *xfer)
1850 {
1851         struct xhci_std_temp temp;
1852         struct xhci_td *td;
1853         uint32_t x;
1854         uint32_t y;
1855         uint8_t mult;
1856
1857         temp.do_isoc_sync = 0;
1858         temp.step_td = 0;
1859         temp.tbc = 0;
1860         temp.tlbpc = 0;
1861         temp.average = xfer->max_hc_frame_size;
1862         temp.max_packet_size = xfer->max_packet_size;
1863         temp.sc = XHCI_BUS2SC(xfer->xroot->bus);
1864         temp.pc = NULL;
1865         temp.last_frame = 0;
1866         temp.offset = 0;
1867         temp.multishort = xfer->flags_int.isochronous_xfr ||
1868             xfer->flags_int.control_xfr ||
1869             xfer->flags_int.short_frames_ok;
1870
1871         /* toggle the DMA set we are using */
1872         xfer->flags_int.curr_dma_set ^= 1;
1873
1874         /* get next DMA set */
1875         td = xfer->td_start[xfer->flags_int.curr_dma_set];
1876
1877         temp.td = NULL;
1878         temp.td_next = td;
1879
1880         xfer->td_transfer_first = td;
1881         xfer->td_transfer_cache = td;
1882
1883         if (xfer->flags_int.isochronous_xfr) {
1884                 uint8_t shift;
1885
1886                 /* compute multiplier for ISOCHRONOUS transfers */
1887                 mult = xfer->endpoint->ecomp ?
1888                     (xfer->endpoint->ecomp->bmAttributes & 3) : 0;
1889                 /* check for USB 2.0 multiplier */
1890                 if (mult == 0) {
1891                         mult = (xfer->endpoint->edesc->
1892                             wMaxPacketSize[1] >> 3) & 3;
1893                 }
1894                 /* range check */
1895                 if (mult > 2)
1896                         mult = 3;
1897                 else
1898                         mult++;
1899
1900                 x = XREAD4(temp.sc, runt, XHCI_MFINDEX);
1901
1902                 DPRINTF("MFINDEX=0x%08x\n", x);
1903
1904                 switch (usbd_get_speed(xfer->xroot->udev)) {
1905                 case USB_SPEED_FULL:
1906                         shift = 3;
1907                         temp.isoc_delta = 8;    /* 1ms */
1908                         x += temp.isoc_delta - 1;
1909                         x &= ~(temp.isoc_delta - 1);
1910                         break;
1911                 default:
1912                         shift = usbd_xfer_get_fps_shift(xfer);
1913                         temp.isoc_delta = 1U << shift;
1914                         x += temp.isoc_delta - 1;
1915                         x &= ~(temp.isoc_delta - 1);
1916                         /* simple frame load balancing */
1917                         x += xfer->endpoint->usb_uframe;
1918                         break;
1919                 }
1920
1921                 y = XHCI_MFINDEX_GET(x - xfer->endpoint->isoc_next);
1922
1923                 if ((xfer->endpoint->is_synced == 0) ||
1924                     (y < (xfer->nframes << shift)) ||
1925                     (XHCI_MFINDEX_GET(-y) >= (128 * 8))) {
1926                         /*
1927                          * If there is data underflow or the pipe
1928                          * queue is empty we schedule the transfer a
1929                          * few frames ahead of the current frame
1930                          * position. Else two isochronous transfers
1931                          * might overlap.
1932                          */
1933                         xfer->endpoint->isoc_next = XHCI_MFINDEX_GET(x + (3 * 8));
1934                         xfer->endpoint->is_synced = 1;
1935                         temp.do_isoc_sync = 1;
1936
1937                         DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next);
1938                 }
1939
1940                 /* compute isochronous completion time */
1941
1942                 y = XHCI_MFINDEX_GET(xfer->endpoint->isoc_next - (x & ~7));
1943
1944                 xfer->isoc_time_complete =
1945                     usb_isoc_time_expand(&temp.sc->sc_bus, x / 8) +
1946                     (y / 8) + (((xfer->nframes << shift) + 7) / 8);
1947
1948                 x = 0;
1949                 temp.isoc_frame = xfer->endpoint->isoc_next;
1950                 temp.trb_type = XHCI_TRB_TYPE_ISOCH;
1951
1952                 xfer->endpoint->isoc_next += xfer->nframes << shift;
1953
1954         } else if (xfer->flags_int.control_xfr) {
1955
1956                 /* check if we should prepend a setup message */
1957
1958                 if (xfer->flags_int.control_hdr) {
1959
1960                         temp.len = xfer->frlengths[0];
1961                         temp.pc = xfer->frbuffers + 0;
1962                         temp.shortpkt = temp.len ? 1 : 0;
1963                         temp.trb_type = XHCI_TRB_TYPE_SETUP_STAGE;
1964                         temp.direction = 0;
1965
1966                         /* check for last frame */
1967                         if (xfer->nframes == 1) {
1968                                 /* no STATUS stage yet, SETUP is last */
1969                                 if (xfer->flags_int.control_act)
1970                                         temp.last_frame = 1;
1971                         }
1972
1973                         xhci_setup_generic_chain_sub(&temp);
1974                 }
1975                 x = 1;
1976                 mult = 1;
1977                 temp.isoc_delta = 0;
1978                 temp.isoc_frame = 0;
1979                 temp.trb_type = XHCI_TRB_TYPE_DATA_STAGE;
1980         } else {
1981                 x = 0;
1982                 mult = 1;
1983                 temp.isoc_delta = 0;
1984                 temp.isoc_frame = 0;
1985                 temp.trb_type = XHCI_TRB_TYPE_NORMAL;
1986         }
1987
1988         if (x != xfer->nframes) {
1989                 /* setup page_cache pointer */
1990                 temp.pc = xfer->frbuffers + x;
1991                 /* set endpoint direction */
1992                 temp.direction = UE_GET_DIR(xfer->endpointno);
1993         }
1994
1995         while (x != xfer->nframes) {
1996
1997                 /* DATA0 / DATA1 message */
1998
1999                 temp.len = xfer->frlengths[x];
2000                 temp.step_td = ((xfer->endpointno & UE_DIR_IN) &&
2001                     x != 0 && temp.multishort == 0);
2002
2003                 x++;
2004
2005                 if (x == xfer->nframes) {
2006                         if (xfer->flags_int.control_xfr) {
2007                                 /* no STATUS stage yet, DATA is last */
2008                                 if (xfer->flags_int.control_act)
2009                                         temp.last_frame = 1;
2010                         } else {
2011                                 temp.last_frame = 1;
2012                         }
2013                 }
2014                 if (temp.len == 0) {
2015
2016                         /* make sure that we send an USB packet */
2017
2018                         temp.shortpkt = 0;
2019
2020                         temp.tbc = 0;
2021                         temp.tlbpc = mult - 1;
2022
2023                 } else if (xfer->flags_int.isochronous_xfr) {
2024
2025                         uint8_t tdpc;
2026
2027                         /*
2028                          * Isochronous transfers don't have short
2029                          * packet termination:
2030                          */
2031
2032                         temp.shortpkt = 1;
2033
2034                         /* isochronous transfers have a transfer limit */
2035
2036                         if (temp.len > xfer->max_frame_size)
2037                                 temp.len = xfer->max_frame_size;
2038
2039                         /* compute TD packet count */
2040                         tdpc = (temp.len + xfer->max_packet_size - 1) /
2041                             xfer->max_packet_size;
2042
2043                         temp.tbc = ((tdpc + mult - 1) / mult) - 1;
2044                         temp.tlbpc = (tdpc % mult);
2045
2046                         if (temp.tlbpc == 0)
2047                                 temp.tlbpc = mult - 1;
2048                         else
2049                                 temp.tlbpc--;
2050                 } else {
2051
2052                         /* regular data transfer */
2053
2054                         temp.shortpkt = xfer->flags.force_short_xfer ? 0 : 1;
2055                 }
2056
2057                 xhci_setup_generic_chain_sub(&temp);
2058
2059                 if (xfer->flags_int.isochronous_xfr) {
2060                         temp.offset += xfer->frlengths[x - 1];
2061                         temp.isoc_frame += temp.isoc_delta;
2062                 } else {
2063                         /* get next Page Cache pointer */
2064                         temp.pc = xfer->frbuffers + x;
2065                 }
2066         }
2067
2068         /* check if we should append a status stage */
2069
2070         if (xfer->flags_int.control_xfr &&
2071             !xfer->flags_int.control_act) {
2072
2073                 /*
2074                  * Send a DATA1 message and invert the current
2075                  * endpoint direction.
2076                  */
2077                 temp.step_td = (xfer->nframes != 0);
2078                 temp.direction = UE_GET_DIR(xfer->endpointno) ^ UE_DIR_IN;
2079                 temp.len = 0;
2080                 temp.pc = NULL;
2081                 temp.shortpkt = 0;
2082                 temp.last_frame = 1;
2083                 temp.trb_type = XHCI_TRB_TYPE_STATUS_STAGE;
2084
2085                 xhci_setup_generic_chain_sub(&temp);
2086         }
2087
2088         td = temp.td;
2089
2090         /* must have at least one frame! */
2091
2092         xfer->td_transfer_last = td;
2093
2094         DPRINTF("first=%p last=%p\n", xfer->td_transfer_first, td);
2095 }
2096
2097 static void
2098 xhci_set_slot_pointer(struct xhci_softc *sc, uint8_t index, uint64_t dev_addr)
2099 {
2100         struct usb_page_search buf_res;
2101         struct xhci_dev_ctx_addr *pdctxa;
2102
2103         usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
2104
2105         pdctxa = buf_res.buffer;
2106
2107         DPRINTF("addr[%u]=0x%016llx\n", index, (long long)dev_addr);
2108
2109         pdctxa->qwBaaDevCtxAddr[index] = htole64(dev_addr);
2110
2111         usb_pc_cpu_flush(&sc->sc_hw.ctx_pc);
2112 }
2113
2114 static usb_error_t
2115 xhci_configure_mask(struct usb_device *udev, uint32_t mask, uint8_t drop)
2116 {
2117         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2118         struct usb_page_search buf_inp;
2119         struct xhci_input_dev_ctx *pinp;
2120         uint32_t temp;
2121         uint8_t index;
2122         uint8_t x;
2123
2124         index = udev->controller_slot_id;
2125
2126         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2127
2128         pinp = buf_inp.buffer;
2129
2130         if (drop) {
2131                 mask &= XHCI_INCTX_NON_CTRL_MASK;
2132                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0, mask);
2133                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, 0);
2134         } else {
2135                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0, 0);
2136                 xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, mask);
2137
2138                 /* find most significant set bit */
2139                 for (x = 31; x != 1; x--) {
2140                         if (mask & (1 << x))
2141                                 break;
2142                 }
2143
2144                 /* adjust */
2145                 x--;
2146
2147                 /* figure out maximum */
2148                 if (x > sc->sc_hw.devs[index].context_num) {
2149                         sc->sc_hw.devs[index].context_num = x;
2150                         temp = xhci_ctx_get_le32(sc, &pinp->ctx_slot.dwSctx0);
2151                         temp &= ~XHCI_SCTX_0_CTX_NUM_SET(31);
2152                         temp |= XHCI_SCTX_0_CTX_NUM_SET(x + 1);
2153                         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2154                 }
2155         }
2156         return (0);
2157 }
2158
2159 static usb_error_t
2160 xhci_configure_endpoint(struct usb_device *udev,
2161     struct usb_endpoint_descriptor *edesc, uint64_t ring_addr,
2162     uint16_t interval, uint8_t max_packet_count, uint8_t mult,
2163     uint8_t fps_shift, uint16_t max_packet_size, uint16_t max_frame_size)
2164 {
2165         struct usb_page_search buf_inp;
2166         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2167         struct xhci_input_dev_ctx *pinp;
2168         uint32_t temp;
2169         uint8_t index;
2170         uint8_t epno;
2171         uint8_t type;
2172
2173         index = udev->controller_slot_id;
2174
2175         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2176
2177         pinp = buf_inp.buffer;
2178
2179         epno = edesc->bEndpointAddress;
2180         type = edesc->bmAttributes & UE_XFERTYPE;
2181
2182         if (type == UE_CONTROL)
2183                 epno |= UE_DIR_IN;
2184
2185         epno = XHCI_EPNO2EPID(epno);
2186
2187         if (epno == 0)
2188                 return (USB_ERR_NO_PIPE);               /* invalid */
2189
2190         if (max_packet_count == 0)
2191                 return (USB_ERR_BAD_BUFSIZE);
2192
2193         max_packet_count--;
2194
2195         if (mult == 0)
2196                 return (USB_ERR_BAD_BUFSIZE);
2197
2198         temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2199             XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
2200             XHCI_EPCTX_0_LSA_SET(0);
2201
2202         switch (udev->speed) {
2203         case USB_SPEED_FULL:
2204         case USB_SPEED_LOW:
2205                 /* 1ms -> 125us */
2206                 fps_shift += 3;
2207                 break;
2208         default:
2209                 break;
2210         }
2211
2212         switch (type) {
2213         case UE_INTERRUPT:
2214                 if (fps_shift > 3)
2215                         fps_shift--;
2216                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2217                 break;
2218         case UE_ISOCHRONOUS:
2219                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2220
2221                 switch (udev->speed) {
2222                 case USB_SPEED_SUPER:
2223                         if (mult > 3)
2224                                 mult = 3;
2225                         temp |= XHCI_EPCTX_0_MULT_SET(mult - 1);
2226                         max_packet_count /= mult;
2227                         break;
2228                 default:
2229                         break;
2230                 }
2231                 break;
2232         default:
2233                 break;
2234         }
2235
2236         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx0, temp);
2237
2238         temp =
2239             XHCI_EPCTX_1_HID_SET(0) |
2240             XHCI_EPCTX_1_MAXB_SET(max_packet_count) |
2241             XHCI_EPCTX_1_MAXP_SIZE_SET(max_packet_size);
2242
2243         if ((udev->parent_hs_hub != NULL) || (udev->address != 0)) {
2244                 if (type != UE_ISOCHRONOUS)
2245                         temp |= XHCI_EPCTX_1_CERR_SET(3);
2246         }
2247
2248         switch (type) {
2249         case UE_CONTROL:
2250                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2251                 break;
2252         case UE_ISOCHRONOUS:
2253                 temp |= XHCI_EPCTX_1_EPTYPE_SET(1);
2254                 break;
2255         case UE_BULK:
2256                 temp |= XHCI_EPCTX_1_EPTYPE_SET(2);
2257                 break;
2258         default:
2259                 temp |= XHCI_EPCTX_1_EPTYPE_SET(3);
2260                 break;
2261         }
2262
2263         /* check for IN direction */
2264         if (epno & 1)
2265                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2266
2267         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx1, temp);
2268
2269         ring_addr |= XHCI_EPCTX_2_DCS_SET(1);
2270
2271         xhci_ctx_set_le64(sc, &pinp->ctx_ep[epno - 1].qwEpCtx2, ring_addr);
2272
2273         switch (edesc->bmAttributes & UE_XFERTYPE) {
2274         case UE_INTERRUPT:
2275         case UE_ISOCHRONOUS:
2276                 temp = XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(max_frame_size) |
2277                     XHCI_EPCTX_4_AVG_TRB_LEN_SET(MIN(XHCI_PAGE_SIZE,
2278                     max_frame_size));
2279                 break;
2280         case UE_CONTROL:
2281                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8);
2282                 break;
2283         default:
2284                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(XHCI_PAGE_SIZE);
2285                 break;
2286         }
2287
2288         xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx4, temp);
2289
2290 #ifdef USB_DEBUG
2291         xhci_dump_endpoint(sc, &pinp->ctx_ep[epno - 1]);
2292 #endif
2293         usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2294
2295         return (0);             /* success */
2296 }
2297
2298 static usb_error_t
2299 xhci_configure_endpoint_by_xfer(struct usb_xfer *xfer)
2300 {
2301         struct xhci_endpoint_ext *pepext;
2302         struct usb_endpoint_ss_comp_descriptor *ecomp;
2303
2304         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2305             xfer->endpoint->edesc);
2306
2307         ecomp = xfer->endpoint->ecomp;
2308
2309         pepext->trb[0].dwTrb3 = 0;      /* halt any transfers */
2310         usb_pc_cpu_flush(pepext->page_cache);
2311
2312         return (xhci_configure_endpoint(xfer->xroot->udev,
2313             xfer->endpoint->edesc, pepext->physaddr,
2314             xfer->interval, xfer->max_packet_count,
2315             (ecomp != NULL) ? (ecomp->bmAttributes & 3) + 1 : 1,
2316             usbd_xfer_get_fps_shift(xfer), xfer->max_packet_size,
2317             xfer->max_frame_size));
2318 }
2319
2320 static usb_error_t
2321 xhci_configure_device(struct usb_device *udev)
2322 {
2323         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2324         struct usb_page_search buf_inp;
2325         struct usb_page_cache *pcinp;
2326         struct xhci_input_dev_ctx *pinp;
2327         struct usb_device *hubdev;
2328         uint32_t temp;
2329         uint32_t route;
2330         uint32_t rh_port;
2331         uint8_t is_hub;
2332         uint8_t index;
2333         uint8_t depth;
2334
2335         index = udev->controller_slot_id;
2336
2337         DPRINTF("index=%u\n", index);
2338
2339         pcinp = &sc->sc_hw.devs[index].input_pc;
2340
2341         usbd_get_page(pcinp, 0, &buf_inp);
2342
2343         pinp = buf_inp.buffer;
2344
2345         rh_port = 0;
2346         route = 0;
2347
2348         /* figure out route string and root HUB port number */
2349
2350         for (hubdev = udev; hubdev != NULL; hubdev = hubdev->parent_hub) {
2351
2352                 if (hubdev->parent_hub == NULL)
2353                         break;
2354
2355                 depth = hubdev->parent_hub->depth;
2356
2357                 /*
2358                  * NOTE: HS/FS/LS devices and the SS root HUB can have
2359                  * more than 15 ports
2360                  */
2361
2362                 rh_port = hubdev->port_no;
2363
2364                 if (depth == 0)
2365                         break;
2366
2367                 if (rh_port > 15)
2368                         rh_port = 15;
2369
2370                 if (depth < 6)
2371                         route |= rh_port << (4 * (depth - 1));
2372         }
2373
2374         DPRINTF("Route=0x%08x\n", route);
2375
2376         temp = XHCI_SCTX_0_ROUTE_SET(route) |
2377             XHCI_SCTX_0_CTX_NUM_SET(
2378             sc->sc_hw.devs[index].context_num + 1);
2379
2380         switch (udev->speed) {
2381         case USB_SPEED_LOW:
2382                 temp |= XHCI_SCTX_0_SPEED_SET(2);
2383                 if (udev->parent_hs_hub != NULL &&
2384                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2385                     UDPROTO_HSHUBMTT) {
2386                         DPRINTF("Device inherits MTT\n");
2387                         temp |= XHCI_SCTX_0_MTT_SET(1);
2388                 }
2389                 break;
2390         case USB_SPEED_HIGH:
2391                 temp |= XHCI_SCTX_0_SPEED_SET(3);
2392                 if (sc->sc_hw.devs[index].nports != 0 &&
2393                     udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) {
2394                         DPRINTF("HUB supports MTT\n");
2395                         temp |= XHCI_SCTX_0_MTT_SET(1);
2396                 }
2397                 break;
2398         case USB_SPEED_FULL:
2399                 temp |= XHCI_SCTX_0_SPEED_SET(1);
2400                 if (udev->parent_hs_hub != NULL &&
2401                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2402                     UDPROTO_HSHUBMTT) {
2403                         DPRINTF("Device inherits MTT\n");
2404                         temp |= XHCI_SCTX_0_MTT_SET(1);
2405                 }
2406                 break;
2407         default:
2408                 temp |= XHCI_SCTX_0_SPEED_SET(4);
2409                 break;
2410         }
2411
2412         is_hub = sc->sc_hw.devs[index].nports != 0 &&
2413             (udev->speed == USB_SPEED_SUPER ||
2414             udev->speed == USB_SPEED_HIGH);
2415
2416         if (is_hub)
2417                 temp |= XHCI_SCTX_0_HUB_SET(1);
2418
2419         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2420
2421         temp = XHCI_SCTX_1_RH_PORT_SET(rh_port);
2422
2423         if (is_hub) {
2424                 temp |= XHCI_SCTX_1_NUM_PORTS_SET(
2425                     sc->sc_hw.devs[index].nports);
2426         }
2427
2428         switch (udev->speed) {
2429         case USB_SPEED_SUPER:
2430                 switch (sc->sc_hw.devs[index].state) {
2431                 case XHCI_ST_ADDRESSED:
2432                 case XHCI_ST_CONFIGURED:
2433                         /* enable power save */
2434                         temp |= XHCI_SCTX_1_MAX_EL_SET(sc->sc_exit_lat_max);
2435                         break;
2436                 default:
2437                         /* disable power save */
2438                         break;
2439                 }
2440                 break;
2441         default:
2442                 break;
2443         }
2444
2445         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx1, temp);
2446
2447         temp = XHCI_SCTX_2_IRQ_TARGET_SET(0);
2448
2449         if (is_hub) {
2450                 temp |= XHCI_SCTX_2_TT_THINK_TIME_SET(
2451                     sc->sc_hw.devs[index].tt);
2452         }
2453
2454         hubdev = udev->parent_hs_hub;
2455
2456         /* check if we should activate the transaction translator */
2457         switch (udev->speed) {
2458         case USB_SPEED_FULL:
2459         case USB_SPEED_LOW:
2460                 if (hubdev != NULL) {
2461                         temp |= XHCI_SCTX_2_TT_HUB_SID_SET(
2462                             hubdev->controller_slot_id);
2463                         temp |= XHCI_SCTX_2_TT_PORT_NUM_SET(
2464                             udev->hs_port_no);
2465                 }
2466                 break;
2467         default:
2468                 break;
2469         }
2470
2471         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx2, temp);
2472
2473         temp = XHCI_SCTX_3_DEV_ADDR_SET(udev->address) |
2474             XHCI_SCTX_3_SLOT_STATE_SET(0);
2475
2476         xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx3, temp);
2477
2478 #ifdef USB_DEBUG
2479         xhci_dump_device(sc, &pinp->ctx_slot);
2480 #endif
2481         usb_pc_cpu_flush(pcinp);
2482
2483         return (0);             /* success */
2484 }
2485
2486 static usb_error_t
2487 xhci_alloc_device_ext(struct usb_device *udev)
2488 {
2489         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2490         struct usb_page_search buf_dev;
2491         struct usb_page_search buf_ep;
2492         struct xhci_trb *trb;
2493         struct usb_page_cache *pc;
2494         struct usb_page *pg;
2495         uint64_t addr;
2496         uint8_t index;
2497         uint8_t i;
2498
2499         index = udev->controller_slot_id;
2500
2501         pc = &sc->sc_hw.devs[index].device_pc;
2502         pg = &sc->sc_hw.devs[index].device_pg;
2503
2504         /* need to initialize the page cache */
2505         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2506
2507         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2508             (2 * sizeof(struct xhci_dev_ctx)) :
2509             sizeof(struct xhci_dev_ctx), XHCI_PAGE_SIZE))
2510                 goto error;
2511
2512         usbd_get_page(pc, 0, &buf_dev);
2513
2514         pc = &sc->sc_hw.devs[index].input_pc;
2515         pg = &sc->sc_hw.devs[index].input_pg;
2516
2517         /* need to initialize the page cache */
2518         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2519
2520         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2521             (2 * sizeof(struct xhci_input_dev_ctx)) :
2522             sizeof(struct xhci_input_dev_ctx), XHCI_PAGE_SIZE)) {
2523                 goto error;
2524         }
2525
2526         pc = &sc->sc_hw.devs[index].endpoint_pc;
2527         pg = &sc->sc_hw.devs[index].endpoint_pg;
2528
2529         /* need to initialize the page cache */
2530         pc->tag_parent = sc->sc_bus.dma_parent_tag;
2531
2532         if (usb_pc_alloc_mem(pc, pg,
2533             sizeof(struct xhci_dev_endpoint_trbs), XHCI_PAGE_SIZE)) {
2534                 goto error;
2535         }
2536
2537         /* initialise all endpoint LINK TRBs */
2538
2539         for (i = 0; i != XHCI_MAX_ENDPOINTS; i++) {
2540
2541                 /* lookup endpoint TRB ring */
2542                 usbd_get_page(pc, (uintptr_t)&
2543                     ((struct xhci_dev_endpoint_trbs *)0)->trb[i][0], &buf_ep);
2544
2545                 /* get TRB pointer */
2546                 trb = buf_ep.buffer;
2547                 trb += XHCI_MAX_TRANSFERS - 1;
2548
2549                 /* get TRB start address */
2550                 addr = buf_ep.physaddr;
2551
2552                 /* create LINK TRB */
2553                 trb->qwTrb0 = htole64(addr);
2554                 trb->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2555                 trb->dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2556                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2557         }
2558
2559         usb_pc_cpu_flush(pc);
2560
2561         xhci_set_slot_pointer(sc, index, buf_dev.physaddr);
2562
2563         return (0);
2564
2565 error:
2566         xhci_free_device_ext(udev);
2567
2568         return (USB_ERR_NOMEM);
2569 }
2570
2571 static void
2572 xhci_free_device_ext(struct usb_device *udev)
2573 {
2574         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2575         uint8_t index;
2576
2577         index = udev->controller_slot_id;
2578         xhci_set_slot_pointer(sc, index, 0);
2579
2580         usb_pc_free_mem(&sc->sc_hw.devs[index].device_pc);
2581         usb_pc_free_mem(&sc->sc_hw.devs[index].input_pc);
2582         usb_pc_free_mem(&sc->sc_hw.devs[index].endpoint_pc);
2583 }
2584
2585 static struct xhci_endpoint_ext *
2586 xhci_get_endpoint_ext(struct usb_device *udev, struct usb_endpoint_descriptor *edesc)
2587 {
2588         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2589         struct xhci_endpoint_ext *pepext;
2590         struct usb_page_cache *pc;
2591         struct usb_page_search buf_ep;
2592         uint8_t epno;
2593         uint8_t index;
2594
2595         epno = edesc->bEndpointAddress;
2596         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
2597                 epno |= UE_DIR_IN;
2598
2599         epno = XHCI_EPNO2EPID(epno);
2600
2601         index = udev->controller_slot_id;
2602
2603         pc = &sc->sc_hw.devs[index].endpoint_pc;
2604
2605         usbd_get_page(pc, (uintptr_t)&((struct xhci_dev_endpoint_trbs *)0)->trb[epno][0], &buf_ep);
2606
2607         pepext = &sc->sc_hw.devs[index].endp[epno];
2608         pepext->page_cache = pc;
2609         pepext->trb = buf_ep.buffer;
2610         pepext->physaddr = buf_ep.physaddr;
2611
2612         return (pepext);
2613 }
2614
2615 static void
2616 xhci_endpoint_doorbell(struct usb_xfer *xfer)
2617 {
2618         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2619         uint8_t epno;
2620         uint8_t index;
2621
2622         epno = xfer->endpointno;
2623         if (xfer->flags_int.control_xfr)
2624                 epno |= UE_DIR_IN;
2625
2626         epno = XHCI_EPNO2EPID(epno);
2627         index = xfer->xroot->udev->controller_slot_id;
2628
2629         if (xfer->xroot->udev->flags.self_suspended == 0) {
2630                 XWRITE4(sc, door, XHCI_DOORBELL(index),
2631                     epno | XHCI_DB_SID_SET(/*xfer->stream_id*/ 0));
2632         }
2633 }
2634
2635 static void
2636 xhci_transfer_remove(struct usb_xfer *xfer, usb_error_t error)
2637 {
2638         struct xhci_endpoint_ext *pepext;
2639
2640         if (xfer->flags_int.bandwidth_reclaimed) {
2641                 xfer->flags_int.bandwidth_reclaimed = 0;
2642
2643                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2644                     xfer->endpoint->edesc);
2645
2646                 pepext->trb_used--;
2647
2648                 pepext->xfer[xfer->qh_pos] = NULL;
2649
2650                 if (error && pepext->trb_running != 0) {
2651                         pepext->trb_halted = 1;
2652                         pepext->trb_running = 0;
2653                 }
2654         }
2655 }
2656
2657 static usb_error_t
2658 xhci_transfer_insert(struct usb_xfer *xfer)
2659 {
2660         struct xhci_td *td_first;
2661         struct xhci_td *td_last;
2662         struct xhci_trb *trb_link;
2663         struct xhci_endpoint_ext *pepext;
2664         uint64_t addr;
2665         uint8_t i;
2666         uint8_t inext;
2667         uint8_t trb_limit;
2668
2669         DPRINTFN(8, "\n");
2670
2671         /* check if already inserted */
2672         if (xfer->flags_int.bandwidth_reclaimed) {
2673                 DPRINTFN(8, "Already in schedule\n");
2674                 return (0);
2675         }
2676
2677         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2678             xfer->endpoint->edesc);
2679
2680         td_first = xfer->td_transfer_first;
2681         td_last = xfer->td_transfer_last;
2682         addr = pepext->physaddr;
2683
2684         switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2685         case UE_CONTROL:
2686         case UE_INTERRUPT:
2687                 /* single buffered */
2688                 trb_limit = 1;
2689                 break;
2690         default:
2691                 /* multi buffered */
2692                 trb_limit = (XHCI_MAX_TRANSFERS - 2);
2693                 break;
2694         }
2695
2696         if (pepext->trb_used >= trb_limit) {
2697                 DPRINTFN(8, "Too many TDs queued.\n");
2698                 return (USB_ERR_NOMEM);
2699         }
2700
2701         /* check for stopped condition, after putting transfer on interrupt queue */
2702         if (pepext->trb_running == 0) {
2703                 struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2704
2705                 DPRINTFN(8, "Not running\n");
2706
2707                 /* start configuration */
2708                 (void)usb_proc_msignal(&sc->sc_config_proc,
2709                     &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2710                 return (0);
2711         }
2712
2713         pepext->trb_used++;
2714
2715         /* get current TRB index */
2716         i = pepext->trb_index;
2717
2718         /* get next TRB index */
2719         inext = (i + 1);
2720
2721         /* the last entry of the ring is a hardcoded link TRB */
2722         if (inext >= (XHCI_MAX_TRANSFERS - 1))
2723                 inext = 0;
2724
2725         /* compute terminating return address */
2726         addr += inext * sizeof(struct xhci_trb);
2727
2728         /* compute link TRB pointer */
2729         trb_link = td_last->td_trb + td_last->ntrb;
2730
2731         /* update next pointer of last link TRB */
2732         trb_link->qwTrb0 = htole64(addr);
2733         trb_link->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2734         trb_link->dwTrb3 = htole32(XHCI_TRB_3_IOC_BIT |
2735             XHCI_TRB_3_CYCLE_BIT |
2736             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2737
2738 #ifdef USB_DEBUG
2739         xhci_dump_trb(&td_last->td_trb[td_last->ntrb]);
2740 #endif
2741         usb_pc_cpu_flush(td_last->page_cache);
2742
2743         /* write ahead chain end marker */
2744
2745         pepext->trb[inext].qwTrb0 = 0;
2746         pepext->trb[inext].dwTrb2 = 0;
2747         pepext->trb[inext].dwTrb3 = 0;
2748
2749         /* update next pointer of link TRB */
2750
2751         pepext->trb[i].qwTrb0 = htole64((uint64_t)td_first->td_self);
2752         pepext->trb[i].dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2753
2754 #ifdef USB_DEBUG
2755         xhci_dump_trb(&pepext->trb[i]);
2756 #endif
2757         usb_pc_cpu_flush(pepext->page_cache);
2758
2759         /* toggle cycle bit which activates the transfer chain */
2760
2761         pepext->trb[i].dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2762             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2763
2764         usb_pc_cpu_flush(pepext->page_cache);
2765
2766         DPRINTF("qh_pos = %u\n", i);
2767
2768         pepext->xfer[i] = xfer;
2769
2770         xfer->qh_pos = i;
2771
2772         xfer->flags_int.bandwidth_reclaimed = 1;
2773
2774         pepext->trb_index = inext;
2775
2776         xhci_endpoint_doorbell(xfer);
2777
2778         return (0);
2779 }
2780
2781 static void
2782 xhci_root_intr(struct xhci_softc *sc)
2783 {
2784         uint16_t i;
2785
2786         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2787
2788         /* clear any old interrupt data */
2789         memset(sc->sc_hub_idata, 0, sizeof(sc->sc_hub_idata));
2790
2791         for (i = 1; i <= sc->sc_noport; i++) {
2792                 /* pick out CHANGE bits from the status register */
2793                 if (XREAD4(sc, oper, XHCI_PORTSC(i)) & (
2794                     XHCI_PS_CSC | XHCI_PS_PEC |
2795                     XHCI_PS_OCC | XHCI_PS_WRC |
2796                     XHCI_PS_PRC | XHCI_PS_PLC |
2797                     XHCI_PS_CEC)) {
2798                         sc->sc_hub_idata[i / 8] |= 1 << (i % 8);
2799                         DPRINTF("port %d changed\n", i);
2800                 }
2801         }
2802         uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
2803             sizeof(sc->sc_hub_idata));
2804 }
2805
2806 /*------------------------------------------------------------------------*
2807  *      xhci_device_done - XHCI done handler
2808  *
2809  * NOTE: This function can be called two times in a row on
2810  * the same USB transfer. From close and from interrupt.
2811  *------------------------------------------------------------------------*/
2812 static void
2813 xhci_device_done(struct usb_xfer *xfer, usb_error_t error)
2814 {
2815         DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
2816             xfer, xfer->endpoint, error);
2817
2818         /* remove transfer from HW queue */
2819         xhci_transfer_remove(xfer, error);
2820
2821         /* dequeue transfer and start next transfer */
2822         usbd_transfer_done(xfer, error);
2823 }
2824
2825 /*------------------------------------------------------------------------*
2826  * XHCI data transfer support (generic type)
2827  *------------------------------------------------------------------------*/
2828 static void
2829 xhci_device_generic_open(struct usb_xfer *xfer)
2830 {
2831         if (xfer->flags_int.isochronous_xfr) {
2832                 switch (xfer->xroot->udev->speed) {
2833                 case USB_SPEED_FULL:
2834                         break;
2835                 default:
2836                         usb_hs_bandwidth_alloc(xfer);
2837                         break;
2838                 }
2839         }
2840 }
2841
2842 static void
2843 xhci_device_generic_close(struct usb_xfer *xfer)
2844 {
2845         DPRINTF("\n");
2846
2847         xhci_device_done(xfer, USB_ERR_CANCELLED);
2848
2849         if (xfer->flags_int.isochronous_xfr) {
2850                 switch (xfer->xroot->udev->speed) {
2851                 case USB_SPEED_FULL:
2852                         break;
2853                 default:
2854                         usb_hs_bandwidth_free(xfer);
2855                         break;
2856                 }
2857         }
2858 }
2859
2860 static void
2861 xhci_device_generic_multi_enter(struct usb_endpoint *ep,
2862     struct usb_xfer *enter_xfer)
2863 {
2864         struct usb_xfer *xfer;
2865
2866         /* check if there is a current transfer */
2867         xfer = ep->endpoint_q.curr;
2868         if (xfer == NULL)
2869                 return;
2870
2871         /*
2872          * Check if the current transfer is started and then pickup
2873          * the next one, if any. Else wait for next start event due to
2874          * block on failure feature.
2875          */
2876         if (!xfer->flags_int.bandwidth_reclaimed)
2877                 return;
2878
2879         xfer = TAILQ_FIRST(&ep->endpoint_q.head);
2880         if (xfer == NULL) {
2881                 /*
2882                  * In case of enter we have to consider that the
2883                  * transfer is queued by the USB core after the enter
2884                  * method is called.
2885                  */
2886                 xfer = enter_xfer;
2887
2888                 if (xfer == NULL)
2889                         return;
2890         }
2891
2892         /* try to multi buffer */
2893         xhci_transfer_insert(xfer);
2894 }
2895
2896 static void
2897 xhci_device_generic_enter(struct usb_xfer *xfer)
2898 {
2899         DPRINTF("\n");
2900
2901         /* setup TD's and QH */
2902         xhci_setup_generic_chain(xfer);
2903
2904         xhci_device_generic_multi_enter(xfer->endpoint, xfer);
2905 }
2906
2907 static void
2908 xhci_device_generic_start(struct usb_xfer *xfer)
2909 {
2910         DPRINTF("\n");
2911
2912         /* try to insert xfer on HW queue */
2913         xhci_transfer_insert(xfer);
2914
2915         /* try to multi buffer */
2916         xhci_device_generic_multi_enter(xfer->endpoint, NULL);
2917
2918         /* add transfer last on interrupt queue */
2919         usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
2920
2921         /* start timeout, if any */
2922         if (xfer->timeout != 0)
2923                 usbd_transfer_timeout_ms(xfer, &xhci_timeout, xfer->timeout);
2924 }
2925
2926 struct usb_pipe_methods xhci_device_generic_methods =
2927 {
2928         .open = xhci_device_generic_open,
2929         .close = xhci_device_generic_close,
2930         .enter = xhci_device_generic_enter,
2931         .start = xhci_device_generic_start,
2932 };
2933
2934 /*------------------------------------------------------------------------*
2935  * xhci root HUB support
2936  *------------------------------------------------------------------------*
2937  * Simulate a hardware HUB by handling all the necessary requests.
2938  *------------------------------------------------------------------------*/
2939
2940 #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) }
2941
2942 static const
2943 struct usb_device_descriptor xhci_devd =
2944 {
2945         .bLength = sizeof(xhci_devd),
2946         .bDescriptorType = UDESC_DEVICE,        /* type */
2947         HSETW(.bcdUSB, 0x0300),                 /* USB version */
2948         .bDeviceClass = UDCLASS_HUB,            /* class */
2949         .bDeviceSubClass = UDSUBCLASS_HUB,      /* subclass */
2950         .bDeviceProtocol = UDPROTO_SSHUB,       /* protocol */
2951         .bMaxPacketSize = 9,                    /* max packet size */
2952         HSETW(.idVendor, 0x0000),               /* vendor */
2953         HSETW(.idProduct, 0x0000),              /* product */
2954         HSETW(.bcdDevice, 0x0100),              /* device version */
2955         .iManufacturer = 1,
2956         .iProduct = 2,
2957         .iSerialNumber = 0,
2958         .bNumConfigurations = 1,                /* # of configurations */
2959 };
2960
2961 static const
2962 struct xhci_bos_desc xhci_bosd = {
2963         .bosd = {
2964                 .bLength = sizeof(xhci_bosd.bosd),
2965                 .bDescriptorType = UDESC_BOS,
2966                 HSETW(.wTotalLength, sizeof(xhci_bosd)),
2967                 .bNumDeviceCaps = 3,
2968         },
2969         .usb2extd = {
2970                 .bLength = sizeof(xhci_bosd.usb2extd),
2971                 .bDescriptorType = 1,
2972                 .bDevCapabilityType = 2,
2973                 .bmAttributes[0] = 2,
2974         },
2975         .usbdcd = {
2976                 .bLength = sizeof(xhci_bosd.usbdcd),
2977                 .bDescriptorType = UDESC_DEVICE_CAPABILITY,
2978                 .bDevCapabilityType = 3,
2979                 .bmAttributes = 0, /* XXX */
2980                 HSETW(.wSpeedsSupported, 0x000C),
2981                 .bFunctionalitySupport = 8,
2982                 .bU1DevExitLat = 255,   /* dummy - not used */
2983                 .wU2DevExitLat = { 0x00, 0x08 },
2984         },
2985         .cidd = {
2986                 .bLength = sizeof(xhci_bosd.cidd),
2987                 .bDescriptorType = 1,
2988                 .bDevCapabilityType = 4,
2989                 .bReserved = 0,
2990                 .bContainerID = 0, /* XXX */
2991         },
2992 };
2993
2994 static const
2995 struct xhci_config_desc xhci_confd = {
2996         .confd = {
2997                 .bLength = sizeof(xhci_confd.confd),
2998                 .bDescriptorType = UDESC_CONFIG,
2999                 .wTotalLength[0] = sizeof(xhci_confd),
3000                 .bNumInterface = 1,
3001                 .bConfigurationValue = 1,
3002                 .iConfiguration = 0,
3003                 .bmAttributes = UC_SELF_POWERED,
3004                 .bMaxPower = 0          /* max power */
3005         },
3006         .ifcd = {
3007                 .bLength = sizeof(xhci_confd.ifcd),
3008                 .bDescriptorType = UDESC_INTERFACE,
3009                 .bNumEndpoints = 1,
3010                 .bInterfaceClass = UICLASS_HUB,
3011                 .bInterfaceSubClass = UISUBCLASS_HUB,
3012                 .bInterfaceProtocol = 0,
3013         },
3014         .endpd = {
3015                 .bLength = sizeof(xhci_confd.endpd),
3016                 .bDescriptorType = UDESC_ENDPOINT,
3017                 .bEndpointAddress = UE_DIR_IN | XHCI_INTR_ENDPT,
3018                 .bmAttributes = UE_INTERRUPT,
3019                 .wMaxPacketSize[0] = 2,         /* max 15 ports */
3020                 .bInterval = 255,
3021         },
3022         .endpcd = {
3023                 .bLength = sizeof(xhci_confd.endpcd),
3024                 .bDescriptorType = UDESC_ENDPOINT_SS_COMP,
3025                 .bMaxBurst = 0,
3026                 .bmAttributes = 0,
3027         },
3028 };
3029
3030 static const
3031 struct usb_hub_ss_descriptor xhci_hubd = {
3032         .bLength = sizeof(xhci_hubd),
3033         .bDescriptorType = UDESC_SS_HUB,
3034 };
3035
3036 static usb_error_t
3037 xhci_roothub_exec(struct usb_device *udev,
3038     struct usb_device_request *req, const void **pptr, uint16_t *plength)
3039 {
3040         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3041         const char *str_ptr;
3042         const void *ptr;
3043         uint32_t port;
3044         uint32_t v;
3045         uint16_t len;
3046         uint16_t i;
3047         uint16_t value;
3048         uint16_t index;
3049         uint8_t j;
3050         usb_error_t err;
3051
3052         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3053
3054         /* buffer reset */
3055         ptr = (const void *)&sc->sc_hub_desc;
3056         len = 0;
3057         err = 0;
3058
3059         value = UGETW(req->wValue);
3060         index = UGETW(req->wIndex);
3061
3062         DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
3063             "wValue=0x%04x wIndex=0x%04x\n",
3064             req->bmRequestType, req->bRequest,
3065             UGETW(req->wLength), value, index);
3066
3067 #define C(x,y) ((x) | ((y) << 8))
3068         switch (C(req->bRequest, req->bmRequestType)) {
3069         case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
3070         case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
3071         case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
3072                 /*
3073                  * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
3074                  * for the integrated root hub.
3075                  */
3076                 break;
3077         case C(UR_GET_CONFIG, UT_READ_DEVICE):
3078                 len = 1;
3079                 sc->sc_hub_desc.temp[0] = sc->sc_conf;
3080                 break;
3081         case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3082                 switch (value >> 8) {
3083                 case UDESC_DEVICE:
3084                         if ((value & 0xff) != 0) {
3085                                 err = USB_ERR_IOERROR;
3086                                 goto done;
3087                         }
3088                         len = sizeof(xhci_devd);
3089                         ptr = (const void *)&xhci_devd;
3090                         break;
3091
3092                 case UDESC_BOS:
3093                         if ((value & 0xff) != 0) {
3094                                 err = USB_ERR_IOERROR;
3095                                 goto done;
3096                         }
3097                         len = sizeof(xhci_bosd);
3098                         ptr = (const void *)&xhci_bosd;
3099                         break;
3100
3101                 case UDESC_CONFIG:
3102                         if ((value & 0xff) != 0) {
3103                                 err = USB_ERR_IOERROR;
3104                                 goto done;
3105                         }
3106                         len = sizeof(xhci_confd);
3107                         ptr = (const void *)&xhci_confd;
3108                         break;
3109
3110                 case UDESC_STRING:
3111                         switch (value & 0xff) {
3112                         case 0: /* Language table */
3113                                 str_ptr = "\001";
3114                                 break;
3115
3116                         case 1: /* Vendor */
3117                                 str_ptr = sc->sc_vendor;
3118                                 break;
3119
3120                         case 2: /* Product */
3121                                 str_ptr = "XHCI root HUB";
3122                                 break;
3123
3124                         default:
3125                                 str_ptr = "";
3126                                 break;
3127                         }
3128
3129                         len = usb_make_str_desc(
3130                             sc->sc_hub_desc.temp,
3131                             sizeof(sc->sc_hub_desc.temp),
3132                             str_ptr);
3133                         break;
3134
3135                 default:
3136                         err = USB_ERR_IOERROR;
3137                         goto done;
3138                 }
3139                 break;
3140         case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
3141                 len = 1;
3142                 sc->sc_hub_desc.temp[0] = 0;
3143                 break;
3144         case C(UR_GET_STATUS, UT_READ_DEVICE):
3145                 len = 2;
3146                 USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
3147                 break;
3148         case C(UR_GET_STATUS, UT_READ_INTERFACE):
3149         case C(UR_GET_STATUS, UT_READ_ENDPOINT):
3150                 len = 2;
3151                 USETW(sc->sc_hub_desc.stat.wStatus, 0);
3152                 break;
3153         case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
3154                 if (value >= XHCI_MAX_DEVICES) {
3155                         err = USB_ERR_IOERROR;
3156                         goto done;
3157                 }
3158                 break;
3159         case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
3160                 if (value != 0 && value != 1) {
3161                         err = USB_ERR_IOERROR;
3162                         goto done;
3163                 }
3164                 sc->sc_conf = value;
3165                 break;
3166         case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
3167                 break;
3168         case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
3169         case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
3170         case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
3171                 err = USB_ERR_IOERROR;
3172                 goto done;
3173         case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
3174                 break;
3175         case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
3176                 break;
3177                 /* Hub requests */
3178         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3179                 break;
3180         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
3181                 DPRINTFN(9, "UR_CLEAR_PORT_FEATURE\n");
3182
3183                 if ((index < 1) ||
3184                     (index > sc->sc_noport)) {
3185                         err = USB_ERR_IOERROR;
3186                         goto done;
3187                 }
3188                 port = XHCI_PORTSC(index);
3189
3190                 v = XREAD4(sc, oper, port);
3191                 i = XHCI_PS_PLS_GET(v);
3192                 v &= ~XHCI_PS_CLEAR;
3193
3194                 switch (value) {
3195                 case UHF_C_BH_PORT_RESET:
3196                         XWRITE4(sc, oper, port, v | XHCI_PS_WRC);
3197                         break;
3198                 case UHF_C_PORT_CONFIG_ERROR:
3199                         XWRITE4(sc, oper, port, v | XHCI_PS_CEC);
3200                         break;
3201                 case UHF_C_PORT_SUSPEND:
3202                 case UHF_C_PORT_LINK_STATE:
3203                         XWRITE4(sc, oper, port, v | XHCI_PS_PLC);
3204                         break;
3205                 case UHF_C_PORT_CONNECTION:
3206                         XWRITE4(sc, oper, port, v | XHCI_PS_CSC);
3207                         break;
3208                 case UHF_C_PORT_ENABLE:
3209                         XWRITE4(sc, oper, port, v | XHCI_PS_PEC);
3210                         break;
3211                 case UHF_C_PORT_OVER_CURRENT:
3212                         XWRITE4(sc, oper, port, v | XHCI_PS_OCC);
3213                         break;
3214                 case UHF_C_PORT_RESET:
3215                         XWRITE4(sc, oper, port, v | XHCI_PS_PRC);
3216                         break;
3217                 case UHF_PORT_ENABLE:
3218                         XWRITE4(sc, oper, port, v | XHCI_PS_PED);
3219                         break;
3220                 case UHF_PORT_POWER:
3221                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PP);
3222                         break;
3223                 case UHF_PORT_INDICATOR:
3224                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PIC_SET(3));
3225                         break;
3226                 case UHF_PORT_SUSPEND:
3227
3228                         /* U3 -> U15 */
3229                         if (i == 3) {
3230                                 XWRITE4(sc, oper, port, v |
3231                                     XHCI_PS_PLS_SET(0xF) | XHCI_PS_LWS);
3232                         }
3233
3234                         /* wait 20ms for resume sequence to complete */
3235                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
3236
3237                         /* U0 */
3238                         XWRITE4(sc, oper, port, v |
3239                             XHCI_PS_PLS_SET(0) | XHCI_PS_LWS);
3240                         break;
3241                 default:
3242                         err = USB_ERR_IOERROR;
3243                         goto done;
3244                 }
3245                 break;
3246
3247         case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3248                 if ((value & 0xff) != 0) {
3249                         err = USB_ERR_IOERROR;
3250                         goto done;
3251                 }
3252
3253                 v = XREAD4(sc, capa, XHCI_HCSPARAMS0);
3254
3255                 sc->sc_hub_desc.hubd = xhci_hubd;
3256
3257                 sc->sc_hub_desc.hubd.bNbrPorts = sc->sc_noport;
3258
3259                 if (XHCI_HCS0_PPC(v))
3260                         i = UHD_PWR_INDIVIDUAL;
3261                 else
3262                         i = UHD_PWR_GANGED;
3263
3264                 if (XHCI_HCS0_PIND(v))
3265                         i |= UHD_PORT_IND;
3266
3267                 i |= UHD_OC_INDIVIDUAL;
3268
3269                 USETW(sc->sc_hub_desc.hubd.wHubCharacteristics, i);
3270
3271                 /* see XHCI section 5.4.9: */
3272                 sc->sc_hub_desc.hubd.bPwrOn2PwrGood = 10;
3273
3274                 for (j = 1; j <= sc->sc_noport; j++) {
3275
3276                         v = XREAD4(sc, oper, XHCI_PORTSC(j));
3277                         if (v & XHCI_PS_DR) {
3278                                 sc->sc_hub_desc.hubd.
3279                                     DeviceRemovable[j / 8] |= 1U << (j % 8);
3280                         }
3281                 }
3282                 len = sc->sc_hub_desc.hubd.bLength;
3283                 break;
3284
3285         case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3286                 len = 16;
3287                 memset(sc->sc_hub_desc.temp, 0, 16);
3288                 break;
3289
3290         case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
3291                 DPRINTFN(9, "UR_GET_STATUS i=%d\n", index);
3292
3293                 if ((index < 1) ||
3294                     (index > sc->sc_noport)) {
3295                         err = USB_ERR_IOERROR;
3296                         goto done;
3297                 }
3298
3299                 v = XREAD4(sc, oper, XHCI_PORTSC(index));
3300
3301                 DPRINTFN(9, "port status=0x%08x\n", v);
3302
3303                 i = UPS_PORT_LINK_STATE_SET(XHCI_PS_PLS_GET(v));
3304
3305                 switch (XHCI_PS_SPEED_GET(v)) {
3306                 case 3:
3307                         i |= UPS_HIGH_SPEED;
3308                         break;
3309                 case 2:
3310                         i |= UPS_LOW_SPEED;
3311                         break;
3312                 case 1:
3313                         /* FULL speed */
3314                         break;
3315                 default:
3316                         i |= UPS_OTHER_SPEED;
3317                         break;
3318                 }
3319
3320                 if (v & XHCI_PS_CCS)
3321                         i |= UPS_CURRENT_CONNECT_STATUS;
3322                 if (v & XHCI_PS_PED)
3323                         i |= UPS_PORT_ENABLED;
3324                 if (v & XHCI_PS_OCA)
3325                         i |= UPS_OVERCURRENT_INDICATOR;
3326                 if (v & XHCI_PS_PR)
3327                         i |= UPS_RESET;
3328                 if (v & XHCI_PS_PP) {
3329                         /*
3330                          * The USB 3.0 RH is using the
3331                          * USB 2.0's power bit
3332                          */
3333                         i |= UPS_PORT_POWER;
3334                 }
3335                 USETW(sc->sc_hub_desc.ps.wPortStatus, i);
3336
3337                 i = 0;
3338                 if (v & XHCI_PS_CSC)
3339                         i |= UPS_C_CONNECT_STATUS;
3340                 if (v & XHCI_PS_PEC)
3341                         i |= UPS_C_PORT_ENABLED;
3342                 if (v & XHCI_PS_OCC)
3343                         i |= UPS_C_OVERCURRENT_INDICATOR;
3344                 if (v & XHCI_PS_WRC)
3345                         i |= UPS_C_BH_PORT_RESET;
3346                 if (v & XHCI_PS_PRC)
3347                         i |= UPS_C_PORT_RESET;
3348                 if (v & XHCI_PS_PLC)
3349                         i |= UPS_C_PORT_LINK_STATE;
3350                 if (v & XHCI_PS_CEC)
3351                         i |= UPS_C_PORT_CONFIG_ERROR;
3352
3353                 USETW(sc->sc_hub_desc.ps.wPortChange, i);
3354                 len = sizeof(sc->sc_hub_desc.ps);
3355                 break;
3356
3357         case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3358                 err = USB_ERR_IOERROR;
3359                 goto done;
3360
3361         case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3362                 break;
3363
3364         case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
3365
3366                 i = index >> 8;
3367                 index &= 0x00FF;
3368
3369                 if ((index < 1) ||
3370                     (index > sc->sc_noport)) {
3371                         err = USB_ERR_IOERROR;
3372                         goto done;
3373                 }
3374
3375                 port = XHCI_PORTSC(index);
3376                 v = XREAD4(sc, oper, port) & ~XHCI_PS_CLEAR;
3377
3378                 switch (value) {
3379                 case UHF_PORT_U1_TIMEOUT:
3380                         if (XHCI_PS_SPEED_GET(v) != 4) {
3381                                 err = USB_ERR_IOERROR;
3382                                 goto done;
3383                         }
3384                         port = XHCI_PORTPMSC(index);
3385                         v = XREAD4(sc, oper, port);
3386                         v &= ~XHCI_PM3_U1TO_SET(0xFF);
3387                         v |= XHCI_PM3_U1TO_SET(i);
3388                         XWRITE4(sc, oper, port, v);
3389                         break;
3390                 case UHF_PORT_U2_TIMEOUT:
3391                         if (XHCI_PS_SPEED_GET(v) != 4) {
3392                                 err = USB_ERR_IOERROR;
3393                                 goto done;
3394                         }
3395                         port = XHCI_PORTPMSC(index);
3396                         v = XREAD4(sc, oper, port);
3397                         v &= ~XHCI_PM3_U2TO_SET(0xFF);
3398                         v |= XHCI_PM3_U2TO_SET(i);
3399                         XWRITE4(sc, oper, port, v);
3400                         break;
3401                 case UHF_BH_PORT_RESET:
3402                         XWRITE4(sc, oper, port, v | XHCI_PS_WPR);
3403                         break;
3404                 case UHF_PORT_LINK_STATE:
3405                         XWRITE4(sc, oper, port, v |
3406                             XHCI_PS_PLS_SET(i) | XHCI_PS_LWS);
3407                         /* 4ms settle time */
3408                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250);
3409                         break;
3410                 case UHF_PORT_ENABLE:
3411                         DPRINTFN(3, "set port enable %d\n", index);
3412                         break;
3413                 case UHF_PORT_SUSPEND:
3414                         DPRINTFN(6, "suspend port %u (LPM=%u)\n", index, i);
3415                         j = XHCI_PS_SPEED_GET(v);
3416                         if ((j < 1) || (j > 3)) {
3417                                 /* non-supported speed */
3418                                 err = USB_ERR_IOERROR;
3419                                 goto done;
3420                         }
3421                         XWRITE4(sc, oper, port, v |
3422                             XHCI_PS_PLS_SET(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
3423                         break;
3424                 case UHF_PORT_RESET:
3425                         DPRINTFN(6, "reset port %d\n", index);
3426                         XWRITE4(sc, oper, port, v | XHCI_PS_PR);
3427                         break;
3428                 case UHF_PORT_POWER:
3429                         DPRINTFN(3, "set port power %d\n", index);
3430                         XWRITE4(sc, oper, port, v | XHCI_PS_PP);
3431                         break;
3432                 case UHF_PORT_TEST:
3433                         DPRINTFN(3, "set port test %d\n", index);
3434                         break;
3435                 case UHF_PORT_INDICATOR:
3436                         DPRINTFN(3, "set port indicator %d\n", index);
3437
3438                         v &= ~XHCI_PS_PIC_SET(3);
3439                         v |= XHCI_PS_PIC_SET(1);
3440
3441                         XWRITE4(sc, oper, port, v);
3442                         break;
3443                 default:
3444                         err = USB_ERR_IOERROR;
3445                         goto done;
3446                 }
3447                 break;
3448
3449         case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
3450         case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
3451         case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
3452         case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
3453                 break;
3454         default:
3455                 err = USB_ERR_IOERROR;
3456                 goto done;
3457         }
3458 done:
3459         *plength = len;
3460         *pptr = ptr;
3461         return (err);
3462 }
3463
3464 static void
3465 xhci_xfer_setup(struct usb_setup_params *parm)
3466 {
3467         struct usb_page_search page_info;
3468         struct usb_page_cache *pc;
3469         struct xhci_softc *sc;
3470         struct usb_xfer *xfer;
3471         void *last_obj;
3472         uint32_t ntd;
3473         uint32_t n;
3474
3475         sc = XHCI_BUS2SC(parm->udev->bus);
3476         xfer = parm->curr_xfer;
3477
3478         /*
3479          * The proof for the "ntd" formula is illustrated like this:
3480          *
3481          * +------------------------------------+
3482          * |                                    |
3483          * |         |remainder ->              |
3484          * |   +-----+---+                      |
3485          * |   | xxx | x | frm 0                |
3486          * |   +-----+---++                     |
3487          * |   | xxx | xx | frm 1               |
3488          * |   +-----+----+                     |
3489          * |            ...                     |
3490          * +------------------------------------+
3491          *
3492          * "xxx" means a completely full USB transfer descriptor
3493          *
3494          * "x" and "xx" means a short USB packet
3495          *
3496          * For the remainder of an USB transfer modulo
3497          * "max_data_length" we need two USB transfer descriptors.
3498          * One to transfer the remaining data and one to finalise with
3499          * a zero length packet in case the "force_short_xfer" flag is
3500          * set. We only need two USB transfer descriptors in the case
3501          * where the transfer length of the first one is a factor of
3502          * "max_frame_size". The rest of the needed USB transfer
3503          * descriptors is given by the buffer size divided by the
3504          * maximum data payload.
3505          */
3506         parm->hc_max_packet_size = 0x400;
3507         parm->hc_max_packet_count = 16 * 3;
3508         parm->hc_max_frame_size = XHCI_TD_PAYLOAD_MAX;
3509
3510         xfer->flags_int.bdma_enable = 1;
3511
3512         usbd_transfer_setup_sub(parm);
3513
3514         if (xfer->flags_int.isochronous_xfr) {
3515                 ntd = ((1 * xfer->nframes)
3516                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3517         } else if (xfer->flags_int.control_xfr) {
3518                 ntd = ((2 * xfer->nframes) + 1  /* STATUS */
3519                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3520         } else {
3521                 ntd = ((2 * xfer->nframes)
3522                     + (xfer->max_data_length / xfer->max_hc_frame_size));
3523         }
3524
3525 alloc_dma_set:
3526
3527         if (parm->err)
3528                 return;
3529
3530         /*
3531          * Allocate queue heads and transfer descriptors
3532          */
3533         last_obj = NULL;
3534
3535         if (usbd_transfer_setup_sub_malloc(
3536             parm, &pc, sizeof(struct xhci_td),
3537             XHCI_TD_ALIGN, ntd)) {
3538                 parm->err = USB_ERR_NOMEM;
3539                 return;
3540         }
3541         if (parm->buf) {
3542                 for (n = 0; n != ntd; n++) {
3543                         struct xhci_td *td;
3544
3545                         usbd_get_page(pc + n, 0, &page_info);
3546
3547                         td = page_info.buffer;
3548
3549                         /* init TD */
3550                         td->td_self = page_info.physaddr;
3551                         td->obj_next = last_obj;
3552                         td->page_cache = pc + n;
3553
3554                         last_obj = td;
3555
3556                         usb_pc_cpu_flush(pc + n);
3557                 }
3558         }
3559         xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
3560
3561         if (!xfer->flags_int.curr_dma_set) {
3562                 xfer->flags_int.curr_dma_set = 1;
3563                 goto alloc_dma_set;
3564         }
3565 }
3566
3567 static usb_error_t
3568 xhci_configure_reset_endpoint(struct usb_xfer *xfer)
3569 {
3570         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3571         struct usb_page_search buf_inp;
3572         struct usb_device *udev;
3573         struct xhci_endpoint_ext *pepext;
3574         struct usb_endpoint_descriptor *edesc;
3575         struct usb_page_cache *pcinp;
3576         usb_error_t err;
3577         uint8_t index;
3578         uint8_t epno;
3579
3580         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3581             xfer->endpoint->edesc);
3582
3583         udev = xfer->xroot->udev;
3584         index = udev->controller_slot_id;
3585
3586         pcinp = &sc->sc_hw.devs[index].input_pc;
3587
3588         usbd_get_page(pcinp, 0, &buf_inp);
3589
3590         edesc = xfer->endpoint->edesc;
3591
3592         epno = edesc->bEndpointAddress;
3593
3594         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
3595                 epno |= UE_DIR_IN;
3596
3597         epno = XHCI_EPNO2EPID(epno);
3598
3599         if (epno == 0)
3600                 return (USB_ERR_NO_PIPE);               /* invalid */
3601
3602         XHCI_CMD_LOCK(sc);
3603
3604         /* configure endpoint */
3605
3606         err = xhci_configure_endpoint_by_xfer(xfer);
3607
3608         if (err != 0) {
3609                 XHCI_CMD_UNLOCK(sc);
3610                 return (err);
3611         }
3612
3613         /*
3614          * Get the endpoint into the stopped state according to the
3615          * endpoint context state diagram in the XHCI specification:
3616          */
3617
3618         err = xhci_cmd_stop_ep(sc, 0, epno, index);
3619
3620         if (err != 0)
3621                 DPRINTF("Could not stop endpoint %u\n", epno);
3622
3623         err = xhci_cmd_reset_ep(sc, 0, epno, index);
3624
3625         if (err != 0)
3626                 DPRINTF("Could not reset endpoint %u\n", epno);
3627
3628         err = xhci_cmd_set_tr_dequeue_ptr(sc, pepext->physaddr |
3629             XHCI_EPCTX_2_DCS_SET(1), 0, epno, index);
3630
3631         if (err != 0)
3632                 DPRINTF("Could not set dequeue ptr for endpoint %u\n", epno);
3633
3634         /*
3635          * Get the endpoint into the running state according to the
3636          * endpoint context state diagram in the XHCI specification:
3637          */
3638
3639         xhci_configure_mask(udev, (1U << epno) | 1U, 0);
3640
3641         err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
3642
3643         if (err != 0)
3644                 DPRINTF("Could not configure endpoint %u\n", epno);
3645
3646         err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
3647
3648         if (err != 0)
3649                 DPRINTF("Could not configure endpoint %u\n", epno);
3650
3651         XHCI_CMD_UNLOCK(sc);
3652
3653         return (0);
3654 }
3655
3656 static void
3657 xhci_xfer_unsetup(struct usb_xfer *xfer)
3658 {
3659         return;
3660 }
3661
3662 static void
3663 xhci_start_dma_delay(struct usb_xfer *xfer)
3664 {
3665         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3666
3667         /* put transfer on interrupt queue (again) */
3668         usbd_transfer_enqueue(&sc->sc_bus.intr_q, xfer);
3669
3670         (void)usb_proc_msignal(&sc->sc_config_proc,
3671             &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
3672 }
3673
3674 static void
3675 xhci_configure_msg(struct usb_proc_msg *pm)
3676 {
3677         struct xhci_softc *sc;
3678         struct xhci_endpoint_ext *pepext;
3679         struct usb_xfer *xfer;
3680
3681         sc = XHCI_BUS2SC(((struct usb_bus_msg *)pm)->bus);
3682
3683 restart:
3684         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3685
3686                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3687                     xfer->endpoint->edesc);
3688
3689                 if ((pepext->trb_halted != 0) ||
3690                     (pepext->trb_running == 0)) {
3691
3692                         uint8_t i;
3693
3694                         /* clear halted and running */
3695                         pepext->trb_halted = 0;
3696                         pepext->trb_running = 0;
3697
3698                         /* nuke remaining buffered transfers */
3699
3700                         for (i = 0; i != (XHCI_MAX_TRANSFERS - 1); i++) {
3701                                 /*
3702                                  * NOTE: We need to use the timeout
3703                                  * error code here else existing
3704                                  * isochronous clients can get
3705                                  * confused:
3706                                  */
3707                                 if (pepext->xfer[i] != NULL) {
3708                                         xhci_device_done(pepext->xfer[i],
3709                                             USB_ERR_TIMEOUT);
3710                                 }
3711                         }
3712
3713                         /*
3714                          * NOTE: The USB transfer cannot vanish in
3715                          * this state!
3716                          */
3717
3718                         USB_BUS_UNLOCK(&sc->sc_bus);
3719
3720                         xhci_configure_reset_endpoint(xfer);
3721
3722                         USB_BUS_LOCK(&sc->sc_bus);
3723
3724                         /* check if halted is still cleared */
3725                         if (pepext->trb_halted == 0) {
3726                                 pepext->trb_running = 1;
3727                                 pepext->trb_index = 0;
3728                         }
3729                         goto restart;
3730                 }
3731
3732                 if (xfer->flags_int.did_dma_delay) {
3733
3734                         /* remove transfer from interrupt queue (again) */
3735                         usbd_transfer_dequeue(xfer);
3736
3737                         /* we are finally done */
3738                         usb_dma_delay_done_cb(xfer);
3739
3740                         /* queue changed - restart */
3741                         goto restart;
3742                 }
3743         }
3744
3745         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3746
3747                 /* try to insert xfer on HW queue */
3748                 xhci_transfer_insert(xfer);
3749
3750                 /* try to multi buffer */
3751                 xhci_device_generic_multi_enter(xfer->endpoint, NULL);
3752         }
3753 }
3754
3755 static void
3756 xhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
3757     struct usb_endpoint *ep)
3758 {
3759         struct xhci_endpoint_ext *pepext;
3760
3761         DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n",
3762             ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode);
3763
3764         if (udev->flags.usb_mode != USB_MODE_HOST) {
3765                 /* not supported */
3766                 return;
3767         }
3768         if (udev->parent_hub == NULL) {
3769                 /* root HUB has special endpoint handling */
3770                 return;
3771         }
3772
3773         ep->methods = &xhci_device_generic_methods;
3774
3775         pepext = xhci_get_endpoint_ext(udev, edesc);
3776
3777         USB_BUS_LOCK(udev->bus);
3778         pepext->trb_halted = 1;
3779         pepext->trb_running = 0;
3780         USB_BUS_UNLOCK(udev->bus);
3781 }
3782
3783 static void
3784 xhci_ep_uninit(struct usb_device *udev, struct usb_endpoint *ep)
3785 {
3786
3787 }
3788
3789 static void
3790 xhci_ep_clear_stall(struct usb_device *udev, struct usb_endpoint *ep)
3791 {
3792         struct xhci_endpoint_ext *pepext;
3793
3794         DPRINTF("\n");
3795
3796         if (udev->flags.usb_mode != USB_MODE_HOST) {
3797                 /* not supported */
3798                 return;
3799         }
3800         if (udev->parent_hub == NULL) {
3801                 /* root HUB has special endpoint handling */
3802                 return;
3803         }
3804
3805         pepext = xhci_get_endpoint_ext(udev, ep->edesc);
3806
3807         USB_BUS_LOCK(udev->bus);
3808         pepext->trb_halted = 1;
3809         pepext->trb_running = 0;
3810         USB_BUS_UNLOCK(udev->bus);
3811 }
3812
3813 static usb_error_t
3814 xhci_device_init(struct usb_device *udev)
3815 {
3816         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3817         usb_error_t err;
3818         uint8_t temp;
3819
3820         /* no init for root HUB */
3821         if (udev->parent_hub == NULL)
3822                 return (0);
3823
3824         XHCI_CMD_LOCK(sc);
3825
3826         /* set invalid default */
3827
3828         udev->controller_slot_id = sc->sc_noslot + 1;
3829
3830         /* try to get a new slot ID from the XHCI */
3831
3832         err = xhci_cmd_enable_slot(sc, &temp);
3833
3834         if (err) {
3835                 XHCI_CMD_UNLOCK(sc);
3836                 return (err);
3837         }
3838
3839         if (temp > sc->sc_noslot) {
3840                 XHCI_CMD_UNLOCK(sc);
3841                 return (USB_ERR_BAD_ADDRESS);
3842         }
3843
3844         if (sc->sc_hw.devs[temp].state != XHCI_ST_DISABLED) {
3845                 DPRINTF("slot %u already allocated.\n", temp);
3846                 XHCI_CMD_UNLOCK(sc);
3847                 return (USB_ERR_BAD_ADDRESS);
3848         }
3849
3850         /* store slot ID for later reference */
3851
3852         udev->controller_slot_id = temp;
3853
3854         /* reset data structure */
3855
3856         memset(&sc->sc_hw.devs[temp], 0, sizeof(sc->sc_hw.devs[0]));
3857
3858         /* set mark slot allocated */
3859
3860         sc->sc_hw.devs[temp].state = XHCI_ST_ENABLED;
3861
3862         err = xhci_alloc_device_ext(udev);
3863
3864         XHCI_CMD_UNLOCK(sc);
3865
3866         /* get device into default state */
3867
3868         if (err == 0)
3869                 err = xhci_set_address(udev, NULL, 0);
3870
3871         return (err);
3872 }
3873
3874 static void
3875 xhci_device_uninit(struct usb_device *udev)
3876 {
3877         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3878         uint8_t index;
3879
3880         /* no init for root HUB */
3881         if (udev->parent_hub == NULL)
3882                 return;
3883
3884         XHCI_CMD_LOCK(sc);
3885
3886         index = udev->controller_slot_id;
3887
3888         if (index <= sc->sc_noslot) {
3889                 xhci_cmd_disable_slot(sc, index);
3890                 sc->sc_hw.devs[index].state = XHCI_ST_DISABLED;
3891
3892                 /* free device extension */
3893                 xhci_free_device_ext(udev);
3894         }
3895
3896         XHCI_CMD_UNLOCK(sc);
3897 }
3898
3899 static void
3900 xhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
3901 {
3902         /*
3903          * Wait until the hardware has finished any possible use of
3904          * the transfer descriptor(s)
3905          */
3906         *pus = 2048;                    /* microseconds */
3907 }
3908
3909 static void
3910 xhci_device_resume(struct usb_device *udev)
3911 {
3912         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3913         uint8_t index;
3914         uint8_t n;
3915         uint8_t p;
3916
3917         DPRINTF("\n");
3918
3919         /* check for root HUB */
3920         if (udev->parent_hub == NULL)
3921                 return;
3922
3923         index = udev->controller_slot_id;
3924
3925         XHCI_CMD_LOCK(sc);
3926
3927         /* blindly resume all endpoints */
3928
3929         USB_BUS_LOCK(udev->bus);
3930
3931         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
3932                 for (p = 0; p != 1 /*XHCI_MAX_STREAMS*/; p++) {
3933                         XWRITE4(sc, door, XHCI_DOORBELL(index),
3934                             n | XHCI_DB_SID_SET(p));
3935                 }
3936         }
3937
3938         USB_BUS_UNLOCK(udev->bus);
3939
3940         XHCI_CMD_UNLOCK(sc);
3941 }
3942
3943 static void
3944 xhci_device_suspend(struct usb_device *udev)
3945 {
3946         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3947         uint8_t index;
3948         uint8_t n;
3949         usb_error_t err;
3950
3951         DPRINTF("\n");
3952
3953         /* check for root HUB */
3954         if (udev->parent_hub == NULL)
3955                 return;
3956
3957         index = udev->controller_slot_id;
3958
3959         XHCI_CMD_LOCK(sc);
3960
3961         /* blindly suspend all endpoints */
3962
3963         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
3964                 err = xhci_cmd_stop_ep(sc, 1, n, index);
3965                 if (err != 0) {
3966                         DPRINTF("Failed to suspend endpoint "
3967                             "%u on slot %u (ignored).\n", n, index);
3968                 }
3969         }
3970
3971         XHCI_CMD_UNLOCK(sc);
3972 }
3973
3974 static void
3975 xhci_set_hw_power(struct usb_bus *bus)
3976 {
3977         DPRINTF("\n");
3978 }
3979
3980 static void
3981 xhci_device_state_change(struct usb_device *udev)
3982 {
3983         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3984         struct usb_page_search buf_inp;
3985         usb_error_t err;
3986         uint8_t index;
3987
3988         /* check for root HUB */
3989         if (udev->parent_hub == NULL)
3990                 return;
3991
3992         index = udev->controller_slot_id;
3993
3994         DPRINTF("\n");
3995
3996         if (usb_get_device_state(udev) == USB_STATE_CONFIGURED) {
3997                 err = uhub_query_info(udev, &sc->sc_hw.devs[index].nports, 
3998                     &sc->sc_hw.devs[index].tt);
3999                 if (err != 0)
4000                         sc->sc_hw.devs[index].nports = 0;
4001         }
4002
4003         XHCI_CMD_LOCK(sc);
4004
4005         switch (usb_get_device_state(udev)) {
4006         case USB_STATE_POWERED:
4007                 if (sc->sc_hw.devs[index].state == XHCI_ST_DEFAULT)
4008                         break;
4009
4010                 /* set default state */
4011                 sc->sc_hw.devs[index].state = XHCI_ST_DEFAULT;
4012
4013                 /* reset number of contexts */
4014                 sc->sc_hw.devs[index].context_num = 0;
4015
4016                 err = xhci_cmd_reset_dev(sc, index);
4017
4018                 if (err != 0) {
4019                         DPRINTF("Device reset failed "
4020                             "for slot %u.\n", index);
4021                 }
4022                 break;
4023
4024         case USB_STATE_ADDRESSED:
4025                 if (sc->sc_hw.devs[index].state == XHCI_ST_ADDRESSED)
4026                         break;
4027
4028                 sc->sc_hw.devs[index].state = XHCI_ST_ADDRESSED;
4029
4030                 err = xhci_cmd_configure_ep(sc, 0, 1, index);
4031
4032                 if (err) {
4033                         DPRINTF("Failed to deconfigure "
4034                             "slot %u.\n", index);
4035                 }
4036                 break;
4037
4038         case USB_STATE_CONFIGURED:
4039                 if (sc->sc_hw.devs[index].state == XHCI_ST_CONFIGURED)
4040                         break;
4041
4042                 /* set configured state */
4043                 sc->sc_hw.devs[index].state = XHCI_ST_CONFIGURED;
4044
4045                 /* reset number of contexts */
4046                 sc->sc_hw.devs[index].context_num = 0;
4047
4048                 usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
4049
4050                 xhci_configure_mask(udev, 3, 0);
4051
4052                 err = xhci_configure_device(udev);
4053                 if (err != 0) {
4054                         DPRINTF("Could not configure device "
4055                             "at slot %u.\n", index);
4056                 }
4057
4058                 err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
4059                 if (err != 0) {
4060                         DPRINTF("Could not evaluate device "
4061                             "context at slot %u.\n", index);
4062                 }
4063                 break;
4064
4065         default:
4066                 break;
4067         }
4068         XHCI_CMD_UNLOCK(sc);
4069 }
4070
4071 struct usb_bus_methods xhci_bus_methods = {
4072         .endpoint_init = xhci_ep_init,
4073         .endpoint_uninit = xhci_ep_uninit,
4074         .xfer_setup = xhci_xfer_setup,
4075         .xfer_unsetup = xhci_xfer_unsetup,
4076         .get_dma_delay = xhci_get_dma_delay,
4077         .device_init = xhci_device_init,
4078         .device_uninit = xhci_device_uninit,
4079         .device_resume = xhci_device_resume,
4080         .device_suspend = xhci_device_suspend,
4081         .set_hw_power = xhci_set_hw_power,
4082         .roothub_exec = xhci_roothub_exec,
4083         .xfer_poll = xhci_do_poll,
4084         .start_dma_delay = xhci_start_dma_delay,
4085         .set_address = xhci_set_address,
4086         .clear_stall = xhci_ep_clear_stall,
4087         .device_state_change = xhci_device_state_change,
4088         .set_hw_power_sleep = xhci_set_hw_power_sleep,
4089 };