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