]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/pci_xhci.c
Add UPDATING entries and bump version.
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / pci_xhci.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2014 Leon Dang <ldang@nahannisys.com>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*
29    XHCI options:
30     -s <n>,xhci,{devices}
31
32    devices:
33      tablet             USB tablet mouse
34  */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/uio.h>
40 #include <sys/types.h>
41 #include <sys/queue.h>
42
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <stdint.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <pthread.h>
49 #include <unistd.h>
50
51 #include <dev/usb/usbdi.h>
52 #include <dev/usb/usb.h>
53 #include <dev/usb/usb_freebsd.h>
54 #include <xhcireg.h>
55
56 #include "bhyverun.h"
57 #include "debug.h"
58 #include "pci_emul.h"
59 #include "pci_xhci.h"
60 #include "usb_emul.h"
61
62
63 static int xhci_debug = 0;
64 #define DPRINTF(params) if (xhci_debug) PRINTLN params
65 #define WPRINTF(params) PRINTLN params
66
67
68 #define XHCI_NAME               "xhci"
69 #define XHCI_MAX_DEVS           8       /* 4 USB3 + 4 USB2 devs */
70
71 #define XHCI_MAX_SLOTS          64      /* min allowed by Windows drivers */
72
73 /*
74  * XHCI data structures can be up to 64k, but limit paddr_guest2host mapping
75  * to 4k to avoid going over the guest physical memory barrier.
76  */
77 #define XHCI_PADDR_SZ           4096    /* paddr_guest2host max size */
78
79 #define XHCI_ERST_MAX           0       /* max 2^entries event ring seg tbl */
80
81 #define XHCI_CAPLEN             (4*8)   /* offset of op register space */
82 #define XHCI_HCCPRAMS2          0x1C    /* offset of HCCPARAMS2 register */
83 #define XHCI_PORTREGS_START     0x400
84 #define XHCI_DOORBELL_MAX       256
85
86 #define XHCI_STREAMS_MAX        1       /* 4-15 in XHCI spec */
87
88 /* caplength and hci-version registers */
89 #define XHCI_SET_CAPLEN(x)              ((x) & 0xFF)
90 #define XHCI_SET_HCIVERSION(x)          (((x) & 0xFFFF) << 16)
91 #define XHCI_GET_HCIVERSION(x)          (((x) >> 16) & 0xFFFF)
92
93 /* hcsparams1 register */
94 #define XHCI_SET_HCSP1_MAXSLOTS(x)      ((x) & 0xFF)
95 #define XHCI_SET_HCSP1_MAXINTR(x)       (((x) & 0x7FF) << 8)
96 #define XHCI_SET_HCSP1_MAXPORTS(x)      (((x) & 0xFF) << 24)
97
98 /* hcsparams2 register */
99 #define XHCI_SET_HCSP2_IST(x)           ((x) & 0x0F)
100 #define XHCI_SET_HCSP2_ERSTMAX(x)       (((x) & 0x0F) << 4)
101 #define XHCI_SET_HCSP2_MAXSCRATCH_HI(x) (((x) & 0x1F) << 21)
102 #define XHCI_SET_HCSP2_MAXSCRATCH_LO(x) (((x) & 0x1F) << 27)
103
104 /* hcsparams3 register */
105 #define XHCI_SET_HCSP3_U1EXITLATENCY(x) ((x) & 0xFF)
106 #define XHCI_SET_HCSP3_U2EXITLATENCY(x) (((x) & 0xFFFF) << 16)
107
108 /* hccparams1 register */
109 #define XHCI_SET_HCCP1_AC64(x)          ((x) & 0x01)
110 #define XHCI_SET_HCCP1_BNC(x)           (((x) & 0x01) << 1)
111 #define XHCI_SET_HCCP1_CSZ(x)           (((x) & 0x01) << 2)
112 #define XHCI_SET_HCCP1_PPC(x)           (((x) & 0x01) << 3)
113 #define XHCI_SET_HCCP1_PIND(x)          (((x) & 0x01) << 4)
114 #define XHCI_SET_HCCP1_LHRC(x)          (((x) & 0x01) << 5)
115 #define XHCI_SET_HCCP1_LTC(x)           (((x) & 0x01) << 6)
116 #define XHCI_SET_HCCP1_NSS(x)           (((x) & 0x01) << 7)
117 #define XHCI_SET_HCCP1_PAE(x)           (((x) & 0x01) << 8)
118 #define XHCI_SET_HCCP1_SPC(x)           (((x) & 0x01) << 9)
119 #define XHCI_SET_HCCP1_SEC(x)           (((x) & 0x01) << 10)
120 #define XHCI_SET_HCCP1_CFC(x)           (((x) & 0x01) << 11)
121 #define XHCI_SET_HCCP1_MAXPSA(x)        (((x) & 0x0F) << 12)
122 #define XHCI_SET_HCCP1_XECP(x)          (((x) & 0xFFFF) << 16)
123
124 /* hccparams2 register */
125 #define XHCI_SET_HCCP2_U3C(x)           ((x) & 0x01)
126 #define XHCI_SET_HCCP2_CMC(x)           (((x) & 0x01) << 1)
127 #define XHCI_SET_HCCP2_FSC(x)           (((x) & 0x01) << 2)
128 #define XHCI_SET_HCCP2_CTC(x)           (((x) & 0x01) << 3)
129 #define XHCI_SET_HCCP2_LEC(x)           (((x) & 0x01) << 4)
130 #define XHCI_SET_HCCP2_CIC(x)           (((x) & 0x01) << 5)
131
132 /* other registers */
133 #define XHCI_SET_DOORBELL(x)            ((x) & ~0x03)
134 #define XHCI_SET_RTSOFFSET(x)           ((x) & ~0x0F)
135
136 /* register masks */
137 #define XHCI_PS_PLS_MASK                (0xF << 5)      /* port link state */
138 #define XHCI_PS_SPEED_MASK              (0xF << 10)     /* port speed */
139 #define XHCI_PS_PIC_MASK                (0x3 << 14)     /* port indicator */
140
141 /* port register set */
142 #define XHCI_PORTREGS_BASE              0x400           /* base offset */
143 #define XHCI_PORTREGS_PORT0             0x3F0
144 #define XHCI_PORTREGS_SETSZ             0x10            /* size of a set */
145
146 #define MASK_64_HI(x)                   ((x) & ~0xFFFFFFFFULL)
147 #define MASK_64_LO(x)                   ((x) & 0xFFFFFFFFULL)
148
149 #define FIELD_REPLACE(a,b,m,s)          (((a) & ~((m) << (s))) | \
150                                         (((b) & (m)) << (s)))
151 #define FIELD_COPY(a,b,m,s)             (((a) & ~((m) << (s))) | \
152                                         (((b) & ((m) << (s)))))
153
154 struct pci_xhci_trb_ring {
155         uint64_t ringaddr;              /* current dequeue guest address */
156         uint32_t ccs;                   /* consumer cycle state */
157 };
158
159 /* device endpoint transfer/stream rings */
160 struct pci_xhci_dev_ep {
161         union {
162                 struct xhci_trb         *_epu_tr;
163                 struct xhci_stream_ctx  *_epu_sctx;
164         } _ep_trbsctx;
165 #define ep_tr           _ep_trbsctx._epu_tr
166 #define ep_sctx         _ep_trbsctx._epu_sctx
167
168         union {
169                 struct pci_xhci_trb_ring _epu_trb;
170                 struct pci_xhci_trb_ring *_epu_sctx_trbs;
171         } _ep_trb_rings;
172 #define ep_ringaddr     _ep_trb_rings._epu_trb.ringaddr
173 #define ep_ccs          _ep_trb_rings._epu_trb.ccs
174 #define ep_sctx_trbs    _ep_trb_rings._epu_sctx_trbs
175
176         struct usb_data_xfer *ep_xfer;  /* transfer chain */
177 };
178
179 /* device context base address array: maps slot->device context */
180 struct xhci_dcbaa {
181         uint64_t dcba[USB_MAX_DEVICES+1]; /* xhci_dev_ctx ptrs */
182 };
183
184 /* port status registers */
185 struct pci_xhci_portregs {
186         uint32_t        portsc;         /* port status and control */
187         uint32_t        portpmsc;       /* port pwr mgmt status & control */
188         uint32_t        portli;         /* port link info */
189         uint32_t        porthlpmc;      /* port hardware LPM control */
190 } __packed;
191 #define XHCI_PS_SPEED_SET(x)    (((x) & 0xF) << 10)
192
193 /* xHC operational registers */
194 struct pci_xhci_opregs {
195         uint32_t        usbcmd;         /* usb command */
196         uint32_t        usbsts;         /* usb status */
197         uint32_t        pgsz;           /* page size */
198         uint32_t        dnctrl;         /* device notification control */
199         uint64_t        crcr;           /* command ring control */
200         uint64_t        dcbaap;         /* device ctx base addr array ptr */
201         uint32_t        config;         /* configure */
202
203         /* guest mapped addresses: */
204         struct xhci_trb *cr_p;          /* crcr dequeue */
205         struct xhci_dcbaa *dcbaa_p;     /* dev ctx array ptr */
206 };
207
208 /* xHC runtime registers */
209 struct pci_xhci_rtsregs {
210         uint32_t        mfindex;        /* microframe index */
211         struct {                        /* interrupter register set */
212                 uint32_t        iman;   /* interrupter management */
213                 uint32_t        imod;   /* interrupter moderation */
214                 uint32_t        erstsz; /* event ring segment table size */
215                 uint32_t        rsvd;
216                 uint64_t        erstba; /* event ring seg-tbl base addr */
217                 uint64_t        erdp;   /* event ring dequeue ptr */
218         } intrreg __packed;
219
220         /* guest mapped addresses */
221         struct xhci_event_ring_seg *erstba_p;
222         struct xhci_trb *erst_p;        /* event ring segment tbl */
223         int             er_deq_seg;     /* event ring dequeue segment */
224         int             er_enq_idx;     /* event ring enqueue index - xHCI */
225         int             er_enq_seg;     /* event ring enqueue segment */
226         uint32_t        er_events_cnt;  /* number of events in ER */
227         uint32_t        event_pcs;      /* producer cycle state flag */
228 };
229
230
231 struct pci_xhci_softc;
232
233
234 /*
235  * USB device emulation container.
236  * This is referenced from usb_hci->hci_sc; 1 pci_xhci_dev_emu for each
237  * emulated device instance.
238  */
239 struct pci_xhci_dev_emu {
240         struct pci_xhci_softc   *xsc;
241
242         /* XHCI contexts */
243         struct xhci_dev_ctx     *dev_ctx;
244         struct pci_xhci_dev_ep  eps[XHCI_MAX_ENDPOINTS];
245         int                     dev_slotstate;
246
247         struct usb_devemu       *dev_ue;        /* USB emulated dev */
248         void                    *dev_sc;        /* device's softc */
249
250         struct usb_hci          hci;
251 };
252
253 struct pci_xhci_softc {
254         struct pci_devinst *xsc_pi;
255
256         pthread_mutex_t mtx;
257
258         uint32_t        caplength;      /* caplen & hciversion */
259         uint32_t        hcsparams1;     /* structural parameters 1 */
260         uint32_t        hcsparams2;     /* structural parameters 2 */
261         uint32_t        hcsparams3;     /* structural parameters 3 */
262         uint32_t        hccparams1;     /* capability parameters 1 */
263         uint32_t        dboff;          /* doorbell offset */
264         uint32_t        rtsoff;         /* runtime register space offset */
265         uint32_t        hccparams2;     /* capability parameters 2 */
266
267         uint32_t        regsend;        /* end of configuration registers */
268
269         struct pci_xhci_opregs  opregs;
270         struct pci_xhci_rtsregs rtsregs;
271
272         struct pci_xhci_portregs *portregs;
273         struct pci_xhci_dev_emu  **devices; /* XHCI[port] = device */
274         struct pci_xhci_dev_emu  **slots;   /* slots assigned from 1 */
275         int             ndevices;
276
277         int             usb2_port_start;
278         int             usb3_port_start;
279 };
280
281
282 /* portregs and devices arrays are set up to start from idx=1 */
283 #define XHCI_PORTREG_PTR(x,n)   &(x)->portregs[(n)]
284 #define XHCI_DEVINST_PTR(x,n)   (x)->devices[(n)]
285 #define XHCI_SLOTDEV_PTR(x,n)   (x)->slots[(n)]
286
287 #define XHCI_HALTED(sc)         ((sc)->opregs.usbsts & XHCI_STS_HCH)
288
289 #define XHCI_GADDR(sc,a)        paddr_guest2host((sc)->xsc_pi->pi_vmctx, \
290                                     (a),                                 \
291                                     XHCI_PADDR_SZ - ((a) & (XHCI_PADDR_SZ-1)))
292
293 static int xhci_in_use;
294
295 /* map USB errors to XHCI */
296 static const int xhci_usb_errors[USB_ERR_MAX] = {
297         [USB_ERR_NORMAL_COMPLETION]     = XHCI_TRB_ERROR_SUCCESS,
298         [USB_ERR_PENDING_REQUESTS]      = XHCI_TRB_ERROR_RESOURCE,
299         [USB_ERR_NOT_STARTED]           = XHCI_TRB_ERROR_ENDP_NOT_ON,
300         [USB_ERR_INVAL]                 = XHCI_TRB_ERROR_INVALID,
301         [USB_ERR_NOMEM]                 = XHCI_TRB_ERROR_RESOURCE,
302         [USB_ERR_CANCELLED]             = XHCI_TRB_ERROR_STOPPED,
303         [USB_ERR_BAD_ADDRESS]           = XHCI_TRB_ERROR_PARAMETER,
304         [USB_ERR_BAD_BUFSIZE]           = XHCI_TRB_ERROR_PARAMETER,
305         [USB_ERR_BAD_FLAG]              = XHCI_TRB_ERROR_PARAMETER,
306         [USB_ERR_NO_CALLBACK]           = XHCI_TRB_ERROR_STALL,
307         [USB_ERR_IN_USE]                = XHCI_TRB_ERROR_RESOURCE,
308         [USB_ERR_NO_ADDR]               = XHCI_TRB_ERROR_RESOURCE,
309         [USB_ERR_NO_PIPE]               = XHCI_TRB_ERROR_RESOURCE,
310         [USB_ERR_ZERO_NFRAMES]          = XHCI_TRB_ERROR_UNDEFINED,
311         [USB_ERR_ZERO_MAXP]             = XHCI_TRB_ERROR_UNDEFINED,
312         [USB_ERR_SET_ADDR_FAILED]       = XHCI_TRB_ERROR_RESOURCE,
313         [USB_ERR_NO_POWER]              = XHCI_TRB_ERROR_ENDP_NOT_ON,
314         [USB_ERR_TOO_DEEP]              = XHCI_TRB_ERROR_RESOURCE,
315         [USB_ERR_IOERROR]               = XHCI_TRB_ERROR_TRB,
316         [USB_ERR_NOT_CONFIGURED]        = XHCI_TRB_ERROR_ENDP_NOT_ON,
317         [USB_ERR_TIMEOUT]               = XHCI_TRB_ERROR_CMD_ABORTED,
318         [USB_ERR_SHORT_XFER]            = XHCI_TRB_ERROR_SHORT_PKT,
319         [USB_ERR_STALLED]               = XHCI_TRB_ERROR_STALL,
320         [USB_ERR_INTERRUPTED]           = XHCI_TRB_ERROR_CMD_ABORTED,
321         [USB_ERR_DMA_LOAD_FAILED]       = XHCI_TRB_ERROR_DATA_BUF,
322         [USB_ERR_BAD_CONTEXT]           = XHCI_TRB_ERROR_TRB,
323         [USB_ERR_NO_ROOT_HUB]           = XHCI_TRB_ERROR_UNDEFINED,
324         [USB_ERR_NO_INTR_THREAD]        = XHCI_TRB_ERROR_UNDEFINED,
325         [USB_ERR_NOT_LOCKED]            = XHCI_TRB_ERROR_UNDEFINED,
326 };
327 #define USB_TO_XHCI_ERR(e)      ((e) < USB_ERR_MAX ? xhci_usb_errors[(e)] : \
328                                 XHCI_TRB_ERROR_INVALID)
329
330 static int pci_xhci_insert_event(struct pci_xhci_softc *sc,
331     struct xhci_trb *evtrb, int do_intr);
332 static void pci_xhci_dump_trb(struct xhci_trb *trb);
333 static void pci_xhci_assert_interrupt(struct pci_xhci_softc *sc);
334 static void pci_xhci_reset_slot(struct pci_xhci_softc *sc, int slot);
335 static void pci_xhci_reset_port(struct pci_xhci_softc *sc, int portn, int warm);
336 static void pci_xhci_update_ep_ring(struct pci_xhci_softc *sc,
337     struct pci_xhci_dev_emu *dev, struct pci_xhci_dev_ep *devep,
338     struct xhci_endp_ctx *ep_ctx, uint32_t streamid,
339     uint64_t ringaddr, int ccs);
340
341 static void
342 pci_xhci_set_evtrb(struct xhci_trb *evtrb, uint64_t port, uint32_t errcode,
343     uint32_t evtype)
344 {
345         evtrb->qwTrb0 = port << 24;
346         evtrb->dwTrb2 = XHCI_TRB_2_ERROR_SET(errcode);
347         evtrb->dwTrb3 = XHCI_TRB_3_TYPE_SET(evtype);
348 }
349
350
351 /* controller reset */
352 static void
353 pci_xhci_reset(struct pci_xhci_softc *sc)
354 {
355         int i;
356
357         sc->rtsregs.er_enq_idx = 0;
358         sc->rtsregs.er_events_cnt = 0;
359         sc->rtsregs.event_pcs = 1;
360
361         for (i = 1; i <= XHCI_MAX_SLOTS; i++) {
362                 pci_xhci_reset_slot(sc, i);
363         }
364 }
365
366 static uint32_t
367 pci_xhci_usbcmd_write(struct pci_xhci_softc *sc, uint32_t cmd)
368 {
369         int do_intr = 0;
370         int i;
371
372         if (cmd & XHCI_CMD_RS) {
373                 do_intr = (sc->opregs.usbcmd & XHCI_CMD_RS) == 0;
374
375                 sc->opregs.usbcmd |= XHCI_CMD_RS;
376                 sc->opregs.usbsts &= ~XHCI_STS_HCH;
377                 sc->opregs.usbsts |= XHCI_STS_PCD;
378
379                 /* Queue port change event on controller run from stop */
380                 if (do_intr)
381                         for (i = 1; i <= XHCI_MAX_DEVS; i++) {
382                                 struct pci_xhci_dev_emu *dev;
383                                 struct pci_xhci_portregs *port;
384                                 struct xhci_trb         evtrb;
385
386                                 if ((dev = XHCI_DEVINST_PTR(sc, i)) == NULL)
387                                         continue;
388
389                                 port = XHCI_PORTREG_PTR(sc, i);
390                                 port->portsc |= XHCI_PS_CSC | XHCI_PS_CCS;
391                                 port->portsc &= ~XHCI_PS_PLS_MASK;
392
393                                 /*
394                                  * XHCI 4.19.3 USB2 RxDetect->Polling,
395                                  *             USB3 Polling->U0
396                                  */
397                                 if (dev->dev_ue->ue_usbver == 2)
398                                         port->portsc |=
399                                             XHCI_PS_PLS_SET(UPS_PORT_LS_POLL);
400                                 else
401                                         port->portsc |=
402                                             XHCI_PS_PLS_SET(UPS_PORT_LS_U0);
403
404                                 pci_xhci_set_evtrb(&evtrb, i,
405                                     XHCI_TRB_ERROR_SUCCESS,
406                                     XHCI_TRB_EVENT_PORT_STS_CHANGE);
407
408                                 if (pci_xhci_insert_event(sc, &evtrb, 0) !=
409                                     XHCI_TRB_ERROR_SUCCESS)
410                                         break;
411                         }
412         } else {
413                 sc->opregs.usbcmd &= ~XHCI_CMD_RS;
414                 sc->opregs.usbsts |= XHCI_STS_HCH;
415                 sc->opregs.usbsts &= ~XHCI_STS_PCD;
416         }
417
418         /* start execution of schedule; stop when set to 0 */
419         cmd |= sc->opregs.usbcmd & XHCI_CMD_RS;
420
421         if (cmd & XHCI_CMD_HCRST) {
422                 /* reset controller */
423                 pci_xhci_reset(sc);
424                 cmd &= ~XHCI_CMD_HCRST;
425         }
426
427         cmd &= ~(XHCI_CMD_CSS | XHCI_CMD_CRS);
428
429         if (do_intr)
430                 pci_xhci_assert_interrupt(sc);
431
432         return (cmd);
433 }
434
435 static void
436 pci_xhci_portregs_write(struct pci_xhci_softc *sc, uint64_t offset,
437     uint64_t value)
438 {
439         struct xhci_trb         evtrb;
440         struct pci_xhci_portregs *p;
441         int port;
442         uint32_t oldpls, newpls;
443
444         if (sc->portregs == NULL)
445                 return;
446
447         port = (offset - XHCI_PORTREGS_PORT0) / XHCI_PORTREGS_SETSZ;
448         offset = (offset - XHCI_PORTREGS_PORT0) % XHCI_PORTREGS_SETSZ;
449
450         DPRINTF(("pci_xhci: portregs wr offset 0x%lx, port %u: 0x%lx",
451                 offset, port, value));
452
453         assert(port >= 0);
454
455         if (port > XHCI_MAX_DEVS) {
456                 DPRINTF(("pci_xhci: portregs_write port %d > ndevices",
457                     port));
458                 return;
459         }
460
461         if (XHCI_DEVINST_PTR(sc, port) == NULL) {
462                 DPRINTF(("pci_xhci: portregs_write to unattached port %d",
463                      port));
464         }
465
466         p = XHCI_PORTREG_PTR(sc, port);
467         switch (offset) {
468         case 0:
469                 /* port reset or warm reset */
470                 if (value & (XHCI_PS_PR | XHCI_PS_WPR)) {
471                         pci_xhci_reset_port(sc, port, value & XHCI_PS_WPR);
472                         break;
473                 }
474
475                 if ((p->portsc & XHCI_PS_PP) == 0) {
476                         WPRINTF(("pci_xhci: portregs_write to unpowered "
477                                  "port %d", port));
478                         break;
479                 }
480
481                 /* Port status and control register  */
482                 oldpls = XHCI_PS_PLS_GET(p->portsc);
483                 newpls = XHCI_PS_PLS_GET(value);
484
485                 p->portsc &= XHCI_PS_PED | XHCI_PS_PLS_MASK |
486                              XHCI_PS_SPEED_MASK | XHCI_PS_PIC_MASK;
487   
488                 if (XHCI_DEVINST_PTR(sc, port))
489                         p->portsc |= XHCI_PS_CCS;
490
491                 p->portsc |= (value &
492                               ~(XHCI_PS_OCA |
493                                 XHCI_PS_PR  |
494                                 XHCI_PS_PED |
495                                 XHCI_PS_PLS_MASK   |    /* link state */
496                                 XHCI_PS_SPEED_MASK |
497                                 XHCI_PS_PIC_MASK   |    /* port indicator */
498                                 XHCI_PS_LWS | XHCI_PS_DR | XHCI_PS_WPR));
499
500                 /* clear control bits */
501                 p->portsc &= ~(value &
502                                (XHCI_PS_CSC |
503                                 XHCI_PS_PEC |
504                                 XHCI_PS_WRC |
505                                 XHCI_PS_OCC |
506                                 XHCI_PS_PRC |
507                                 XHCI_PS_PLC |
508                                 XHCI_PS_CEC |
509                                 XHCI_PS_CAS));
510
511                 /* port disable request; for USB3, don't care */
512                 if (value & XHCI_PS_PED)
513                         DPRINTF(("Disable port %d request", port));
514
515                 if (!(value & XHCI_PS_LWS))
516                         break;
517
518                 DPRINTF(("Port new PLS: %d", newpls));
519                 switch (newpls) {
520                 case 0: /* U0 */
521                 case 3: /* U3 */
522                         if (oldpls != newpls) {
523                                 p->portsc &= ~XHCI_PS_PLS_MASK;
524                                 p->portsc |= XHCI_PS_PLS_SET(newpls) |
525                                              XHCI_PS_PLC;
526
527                                 if (oldpls != 0 && newpls == 0) {
528                                         pci_xhci_set_evtrb(&evtrb, port,
529                                             XHCI_TRB_ERROR_SUCCESS,
530                                             XHCI_TRB_EVENT_PORT_STS_CHANGE);
531
532                                         pci_xhci_insert_event(sc, &evtrb, 1);
533                                 }
534                         }
535                         break;
536
537                 default:
538                         DPRINTF(("Unhandled change port %d PLS %u",
539                                  port, newpls));
540                         break;
541                 }
542                 break;
543         case 4: 
544                 /* Port power management status and control register  */
545                 p->portpmsc = value;
546                 break;
547         case 8:
548                 /* Port link information register */
549                 DPRINTF(("pci_xhci attempted write to PORTLI, port %d",
550                         port));
551                 break;
552         case 12:
553                 /*
554                  * Port hardware LPM control register.
555                  * For USB3, this register is reserved.
556                  */
557                 p->porthlpmc = value;
558                 break;
559         }
560 }
561
562 struct xhci_dev_ctx *
563 pci_xhci_get_dev_ctx(struct pci_xhci_softc *sc, uint32_t slot)
564 {
565         uint64_t devctx_addr;
566         struct xhci_dev_ctx *devctx;
567
568         assert(slot > 0 && slot <= sc->ndevices);
569         assert(sc->opregs.dcbaa_p != NULL);
570
571         devctx_addr = sc->opregs.dcbaa_p->dcba[slot];
572
573         if (devctx_addr == 0) {
574                 DPRINTF(("get_dev_ctx devctx_addr == 0"));
575                 return (NULL);
576         }
577
578         DPRINTF(("pci_xhci: get dev ctx, slot %u devctx addr %016lx",
579                 slot, devctx_addr));
580         devctx = XHCI_GADDR(sc, devctx_addr & ~0x3FUL);
581
582         return (devctx);
583 }
584
585 struct xhci_trb *
586 pci_xhci_trb_next(struct pci_xhci_softc *sc, struct xhci_trb *curtrb,
587     uint64_t *guestaddr)
588 {
589         struct xhci_trb *next;
590
591         assert(curtrb != NULL);
592
593         if (XHCI_TRB_3_TYPE_GET(curtrb->dwTrb3) == XHCI_TRB_TYPE_LINK) {
594                 if (guestaddr)
595                         *guestaddr = curtrb->qwTrb0 & ~0xFUL;
596                 
597                 next = XHCI_GADDR(sc, curtrb->qwTrb0 & ~0xFUL);
598         } else {
599                 if (guestaddr)
600                         *guestaddr += sizeof(struct xhci_trb) & ~0xFUL;
601
602                 next = curtrb + 1;
603         }
604
605         return (next);
606 }
607
608 static void
609 pci_xhci_assert_interrupt(struct pci_xhci_softc *sc)
610 {
611
612         sc->rtsregs.intrreg.erdp |= XHCI_ERDP_LO_BUSY;
613         sc->rtsregs.intrreg.iman |= XHCI_IMAN_INTR_PEND;
614         sc->opregs.usbsts |= XHCI_STS_EINT;
615
616         /* only trigger interrupt if permitted */
617         if ((sc->opregs.usbcmd & XHCI_CMD_INTE) &&
618             (sc->rtsregs.intrreg.iman & XHCI_IMAN_INTR_ENA)) {
619                 if (pci_msi_enabled(sc->xsc_pi))
620                         pci_generate_msi(sc->xsc_pi, 0);
621                 else
622                         pci_lintr_assert(sc->xsc_pi);
623         }
624 }
625
626 static void
627 pci_xhci_deassert_interrupt(struct pci_xhci_softc *sc)
628 {
629
630         if (!pci_msi_enabled(sc->xsc_pi))
631                 pci_lintr_assert(sc->xsc_pi);
632 }
633
634 static void
635 pci_xhci_init_ep(struct pci_xhci_dev_emu *dev, int epid)
636 {
637         struct xhci_dev_ctx    *dev_ctx;
638         struct pci_xhci_dev_ep *devep;
639         struct xhci_endp_ctx   *ep_ctx;
640         uint32_t        pstreams;
641         int             i;
642
643         dev_ctx = dev->dev_ctx;
644         ep_ctx = &dev_ctx->ctx_ep[epid];
645         devep = &dev->eps[epid];
646         pstreams = XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0);
647         if (pstreams > 0) {
648                 DPRINTF(("init_ep %d with pstreams %d", epid, pstreams));
649                 assert(devep->ep_sctx_trbs == NULL);
650
651                 devep->ep_sctx = XHCI_GADDR(dev->xsc, ep_ctx->qwEpCtx2 &
652                                             XHCI_EPCTX_2_TR_DQ_PTR_MASK);
653                 devep->ep_sctx_trbs = calloc(pstreams,
654                                       sizeof(struct pci_xhci_trb_ring));
655                 for (i = 0; i < pstreams; i++) {
656                         devep->ep_sctx_trbs[i].ringaddr =
657                                                  devep->ep_sctx[i].qwSctx0 &
658                                                  XHCI_SCTX_0_TR_DQ_PTR_MASK;
659                         devep->ep_sctx_trbs[i].ccs =
660                              XHCI_SCTX_0_DCS_GET(devep->ep_sctx[i].qwSctx0);
661                 }
662         } else {
663                 DPRINTF(("init_ep %d with no pstreams", epid));
664                 devep->ep_ringaddr = ep_ctx->qwEpCtx2 &
665                                      XHCI_EPCTX_2_TR_DQ_PTR_MASK;
666                 devep->ep_ccs = XHCI_EPCTX_2_DCS_GET(ep_ctx->qwEpCtx2);
667                 devep->ep_tr = XHCI_GADDR(dev->xsc, devep->ep_ringaddr);
668                 DPRINTF(("init_ep tr DCS %x", devep->ep_ccs));
669         }
670
671         if (devep->ep_xfer == NULL) {
672                 devep->ep_xfer = malloc(sizeof(struct usb_data_xfer));
673                 USB_DATA_XFER_INIT(devep->ep_xfer);
674         }
675 }
676
677 static void
678 pci_xhci_disable_ep(struct pci_xhci_dev_emu *dev, int epid)
679 {
680         struct xhci_dev_ctx    *dev_ctx;
681         struct pci_xhci_dev_ep *devep;
682         struct xhci_endp_ctx   *ep_ctx;
683
684         DPRINTF(("pci_xhci disable_ep %d", epid));
685
686         dev_ctx = dev->dev_ctx;
687         ep_ctx = &dev_ctx->ctx_ep[epid];
688         ep_ctx->dwEpCtx0 = (ep_ctx->dwEpCtx0 & ~0x7) | XHCI_ST_EPCTX_DISABLED;
689
690         devep = &dev->eps[epid];
691         if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) > 0 &&
692             devep->ep_sctx_trbs != NULL)
693                         free(devep->ep_sctx_trbs);
694
695         if (devep->ep_xfer != NULL) {
696                 free(devep->ep_xfer);
697                 devep->ep_xfer = NULL;
698         }
699
700         memset(devep, 0, sizeof(struct pci_xhci_dev_ep));
701 }
702
703
704 /* reset device at slot and data structures related to it */
705 static void
706 pci_xhci_reset_slot(struct pci_xhci_softc *sc, int slot)
707 {
708         struct pci_xhci_dev_emu *dev;
709
710         dev = XHCI_SLOTDEV_PTR(sc, slot);
711
712         if (!dev) {
713                 DPRINTF(("xhci reset unassigned slot (%d)?", slot));
714         } else {
715                 dev->dev_slotstate = XHCI_ST_DISABLED;
716         }
717
718         /* TODO: reset ring buffer pointers */
719 }
720
721 static int
722 pci_xhci_insert_event(struct pci_xhci_softc *sc, struct xhci_trb *evtrb,
723     int do_intr)
724 {
725         struct pci_xhci_rtsregs *rts;
726         uint64_t        erdp;
727         int             erdp_idx;
728         int             err;
729         struct xhci_trb *evtrbptr;
730
731         err = XHCI_TRB_ERROR_SUCCESS;
732
733         rts = &sc->rtsregs;
734
735         erdp = rts->intrreg.erdp & ~0xF;
736         erdp_idx = (erdp - rts->erstba_p[rts->er_deq_seg].qwEvrsTablePtr) /
737                    sizeof(struct xhci_trb);
738
739         DPRINTF(("pci_xhci: insert event 0[%lx] 2[%x] 3[%x]",
740                  evtrb->qwTrb0, evtrb->dwTrb2, evtrb->dwTrb3));
741         DPRINTF(("\terdp idx %d/seg %d, enq idx %d/seg %d, pcs %u",
742                  erdp_idx, rts->er_deq_seg, rts->er_enq_idx,
743                  rts->er_enq_seg, rts->event_pcs));
744         DPRINTF(("\t(erdp=0x%lx, erst=0x%lx, tblsz=%u, do_intr %d)",
745                  erdp, rts->erstba_p->qwEvrsTablePtr,
746                  rts->erstba_p->dwEvrsTableSize, do_intr));
747
748         evtrbptr = &rts->erst_p[rts->er_enq_idx];
749
750         /* TODO: multi-segment table */
751         if (rts->er_events_cnt >= rts->erstba_p->dwEvrsTableSize) {
752                 DPRINTF(("pci_xhci[%d] cannot insert event; ring full",
753                          __LINE__));
754                 err = XHCI_TRB_ERROR_EV_RING_FULL;
755                 goto done;
756         }
757
758         if (rts->er_events_cnt == rts->erstba_p->dwEvrsTableSize - 1) {
759                 struct xhci_trb errev;
760
761                 if ((evtrbptr->dwTrb3 & 0x1) == (rts->event_pcs & 0x1)) {
762
763                         DPRINTF(("pci_xhci[%d] insert evt err: ring full",
764                                  __LINE__));
765
766                         errev.qwTrb0 = 0;
767                         errev.dwTrb2 = XHCI_TRB_2_ERROR_SET(
768                                             XHCI_TRB_ERROR_EV_RING_FULL);
769                         errev.dwTrb3 = XHCI_TRB_3_TYPE_SET(
770                                             XHCI_TRB_EVENT_HOST_CTRL) |
771                                        rts->event_pcs;
772                         rts->er_events_cnt++;
773                         memcpy(&rts->erst_p[rts->er_enq_idx], &errev,
774                                sizeof(struct xhci_trb));
775                         rts->er_enq_idx = (rts->er_enq_idx + 1) %
776                                           rts->erstba_p->dwEvrsTableSize;
777                         err = XHCI_TRB_ERROR_EV_RING_FULL;
778                         do_intr = 1;
779
780                         goto done;
781                 }
782         } else {
783                 rts->er_events_cnt++;
784         }
785
786         evtrb->dwTrb3 &= ~XHCI_TRB_3_CYCLE_BIT;
787         evtrb->dwTrb3 |= rts->event_pcs;
788
789         memcpy(&rts->erst_p[rts->er_enq_idx], evtrb, sizeof(struct xhci_trb));
790         rts->er_enq_idx = (rts->er_enq_idx + 1) %
791                           rts->erstba_p->dwEvrsTableSize;
792
793         if (rts->er_enq_idx == 0)
794                 rts->event_pcs ^= 1;
795
796 done:
797         if (do_intr)
798                 pci_xhci_assert_interrupt(sc);
799
800         return (err);
801 }
802
803 static uint32_t
804 pci_xhci_cmd_enable_slot(struct pci_xhci_softc *sc, uint32_t *slot)
805 {
806         struct pci_xhci_dev_emu *dev;
807         uint32_t        cmderr;
808         int             i;
809
810         cmderr = XHCI_TRB_ERROR_NO_SLOTS;
811         if (sc->portregs != NULL)
812                 for (i = 1; i <= XHCI_MAX_SLOTS; i++) {
813                         dev = XHCI_SLOTDEV_PTR(sc, i);
814                         if (dev && dev->dev_slotstate == XHCI_ST_DISABLED) {
815                                 *slot = i;
816                                 dev->dev_slotstate = XHCI_ST_ENABLED;
817                                 cmderr = XHCI_TRB_ERROR_SUCCESS;
818                                 dev->hci.hci_address = i;
819                                 break;
820                         }
821                 }
822
823         DPRINTF(("pci_xhci enable slot (error=%d) slot %u",
824                 cmderr != XHCI_TRB_ERROR_SUCCESS, *slot));
825
826         return (cmderr);
827 }
828
829 static uint32_t
830 pci_xhci_cmd_disable_slot(struct pci_xhci_softc *sc, uint32_t slot)
831 {
832         struct pci_xhci_dev_emu *dev;
833         uint32_t cmderr;
834
835         DPRINTF(("pci_xhci disable slot %u", slot));
836
837         cmderr = XHCI_TRB_ERROR_NO_SLOTS;
838         if (sc->portregs == NULL)
839                 goto done;
840
841         if (slot > sc->ndevices) {
842                 cmderr = XHCI_TRB_ERROR_SLOT_NOT_ON;
843                 goto done;
844         }
845
846         dev = XHCI_SLOTDEV_PTR(sc, slot);
847         if (dev) {
848                 if (dev->dev_slotstate == XHCI_ST_DISABLED) {
849                         cmderr = XHCI_TRB_ERROR_SLOT_NOT_ON;
850                 } else {
851                         dev->dev_slotstate = XHCI_ST_DISABLED;
852                         cmderr = XHCI_TRB_ERROR_SUCCESS;
853                         /* TODO: reset events and endpoints */
854                 }
855         }
856
857 done:
858         return (cmderr);
859 }
860
861 static uint32_t
862 pci_xhci_cmd_reset_device(struct pci_xhci_softc *sc, uint32_t slot)
863 {
864         struct pci_xhci_dev_emu *dev;
865         struct xhci_dev_ctx     *dev_ctx;
866         struct xhci_endp_ctx    *ep_ctx;
867         uint32_t        cmderr;
868         int             i;
869
870         cmderr = XHCI_TRB_ERROR_NO_SLOTS;
871         if (sc->portregs == NULL)
872                 goto done;
873
874         DPRINTF(("pci_xhci reset device slot %u", slot));
875
876         dev = XHCI_SLOTDEV_PTR(sc, slot);
877         if (!dev || dev->dev_slotstate == XHCI_ST_DISABLED)
878                 cmderr = XHCI_TRB_ERROR_SLOT_NOT_ON;
879         else {
880                 dev->dev_slotstate = XHCI_ST_DEFAULT;
881
882                 dev->hci.hci_address = 0;
883                 dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
884
885                 /* slot state */
886                 dev_ctx->ctx_slot.dwSctx3 = FIELD_REPLACE(
887                     dev_ctx->ctx_slot.dwSctx3, XHCI_ST_SLCTX_DEFAULT,
888                     0x1F, 27);
889
890                 /* number of contexts */
891                 dev_ctx->ctx_slot.dwSctx0 = FIELD_REPLACE(
892                     dev_ctx->ctx_slot.dwSctx0, 1, 0x1F, 27);
893
894                 /* reset all eps other than ep-0 */
895                 for (i = 2; i <= 31; i++) {
896                         ep_ctx = &dev_ctx->ctx_ep[i];
897                         ep_ctx->dwEpCtx0 = FIELD_REPLACE( ep_ctx->dwEpCtx0,
898                             XHCI_ST_EPCTX_DISABLED, 0x7, 0);
899                 }
900
901                 cmderr = XHCI_TRB_ERROR_SUCCESS;
902         }
903
904         pci_xhci_reset_slot(sc, slot);
905
906 done:
907         return (cmderr);
908 }
909
910 static uint32_t
911 pci_xhci_cmd_address_device(struct pci_xhci_softc *sc, uint32_t slot,
912     struct xhci_trb *trb)
913 {
914         struct pci_xhci_dev_emu *dev;
915         struct xhci_input_dev_ctx *input_ctx;
916         struct xhci_slot_ctx    *islot_ctx;
917         struct xhci_dev_ctx     *dev_ctx;
918         struct xhci_endp_ctx    *ep0_ctx;
919         uint32_t                cmderr;
920
921         input_ctx = XHCI_GADDR(sc, trb->qwTrb0 & ~0xFUL);
922         islot_ctx = &input_ctx->ctx_slot;
923         ep0_ctx = &input_ctx->ctx_ep[1];
924
925         cmderr = XHCI_TRB_ERROR_SUCCESS;
926
927         DPRINTF(("pci_xhci: address device, input ctl: D 0x%08x A 0x%08x,",
928                 input_ctx->ctx_input.dwInCtx0, input_ctx->ctx_input.dwInCtx1));
929         DPRINTF(("          slot %08x %08x %08x %08x",
930                 islot_ctx->dwSctx0, islot_ctx->dwSctx1,
931                 islot_ctx->dwSctx2, islot_ctx->dwSctx3));
932         DPRINTF(("          ep0  %08x %08x %016lx %08x",
933                 ep0_ctx->dwEpCtx0, ep0_ctx->dwEpCtx1, ep0_ctx->qwEpCtx2,
934                 ep0_ctx->dwEpCtx4));
935
936         /* when setting address: drop-ctx=0, add-ctx=slot+ep0 */
937         if ((input_ctx->ctx_input.dwInCtx0 != 0) ||
938             (input_ctx->ctx_input.dwInCtx1 & 0x03) != 0x03) {
939                 DPRINTF(("pci_xhci: address device, input ctl invalid"));
940                 cmderr = XHCI_TRB_ERROR_TRB;
941                 goto done;
942         }
943
944         /* assign address to slot */
945         dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
946
947         DPRINTF(("pci_xhci: address device, dev ctx"));
948         DPRINTF(("          slot %08x %08x %08x %08x",
949                 dev_ctx->ctx_slot.dwSctx0, dev_ctx->ctx_slot.dwSctx1,
950                 dev_ctx->ctx_slot.dwSctx2, dev_ctx->ctx_slot.dwSctx3));
951
952         dev = XHCI_SLOTDEV_PTR(sc, slot);
953         assert(dev != NULL);
954
955         dev->hci.hci_address = slot;
956         dev->dev_ctx = dev_ctx;
957
958         if (dev->dev_ue->ue_reset == NULL ||
959             dev->dev_ue->ue_reset(dev->dev_sc) < 0) {
960                 cmderr = XHCI_TRB_ERROR_ENDP_NOT_ON;
961                 goto done;
962         }
963
964         memcpy(&dev_ctx->ctx_slot, islot_ctx, sizeof(struct xhci_slot_ctx));
965
966         dev_ctx->ctx_slot.dwSctx3 =
967             XHCI_SCTX_3_SLOT_STATE_SET(XHCI_ST_SLCTX_ADDRESSED) |
968             XHCI_SCTX_3_DEV_ADDR_SET(slot);
969
970         memcpy(&dev_ctx->ctx_ep[1], ep0_ctx, sizeof(struct xhci_endp_ctx));
971         ep0_ctx = &dev_ctx->ctx_ep[1];
972         ep0_ctx->dwEpCtx0 = (ep0_ctx->dwEpCtx0 & ~0x7) |
973             XHCI_EPCTX_0_EPSTATE_SET(XHCI_ST_EPCTX_RUNNING);
974
975         pci_xhci_init_ep(dev, 1);
976
977         dev->dev_slotstate = XHCI_ST_ADDRESSED;
978
979         DPRINTF(("pci_xhci: address device, output ctx"));
980         DPRINTF(("          slot %08x %08x %08x %08x",
981                 dev_ctx->ctx_slot.dwSctx0, dev_ctx->ctx_slot.dwSctx1,
982                 dev_ctx->ctx_slot.dwSctx2, dev_ctx->ctx_slot.dwSctx3));
983         DPRINTF(("          ep0  %08x %08x %016lx %08x",
984                 ep0_ctx->dwEpCtx0, ep0_ctx->dwEpCtx1, ep0_ctx->qwEpCtx2,
985                 ep0_ctx->dwEpCtx4));
986
987 done:
988         return (cmderr);
989 }
990
991 static uint32_t
992 pci_xhci_cmd_config_ep(struct pci_xhci_softc *sc, uint32_t slot,
993     struct xhci_trb *trb)
994 {
995         struct xhci_input_dev_ctx *input_ctx;
996         struct pci_xhci_dev_emu *dev;
997         struct xhci_dev_ctx     *dev_ctx;
998         struct xhci_endp_ctx    *ep_ctx, *iep_ctx;
999         uint32_t        cmderr;
1000         int             i;
1001
1002         cmderr = XHCI_TRB_ERROR_SUCCESS;
1003
1004         DPRINTF(("pci_xhci config_ep slot %u", slot));
1005
1006         dev = XHCI_SLOTDEV_PTR(sc, slot);
1007         assert(dev != NULL);
1008
1009         if ((trb->dwTrb3 & XHCI_TRB_3_DCEP_BIT) != 0) {
1010                 DPRINTF(("pci_xhci config_ep - deconfigure ep slot %u",
1011                         slot));
1012                 if (dev->dev_ue->ue_stop != NULL)
1013                         dev->dev_ue->ue_stop(dev->dev_sc);
1014
1015                 dev->dev_slotstate = XHCI_ST_ADDRESSED;
1016
1017                 dev->hci.hci_address = 0;
1018                 dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
1019
1020                 /* number of contexts */
1021                 dev_ctx->ctx_slot.dwSctx0 = FIELD_REPLACE(
1022                     dev_ctx->ctx_slot.dwSctx0, 1, 0x1F, 27);
1023
1024                 /* slot state */
1025                 dev_ctx->ctx_slot.dwSctx3 = FIELD_REPLACE(
1026                     dev_ctx->ctx_slot.dwSctx3, XHCI_ST_SLCTX_ADDRESSED,
1027                     0x1F, 27);
1028
1029                 /* disable endpoints */
1030                 for (i = 2; i < 32; i++)
1031                         pci_xhci_disable_ep(dev, i);
1032
1033                 cmderr = XHCI_TRB_ERROR_SUCCESS;
1034
1035                 goto done;
1036         }
1037
1038         if (dev->dev_slotstate < XHCI_ST_ADDRESSED) {
1039                 DPRINTF(("pci_xhci: config_ep slotstate x%x != addressed",
1040                         dev->dev_slotstate));
1041                 cmderr = XHCI_TRB_ERROR_SLOT_NOT_ON;
1042                 goto done;
1043         }
1044
1045         /* In addressed/configured state;
1046          * for each drop endpoint ctx flag:
1047          *   ep->state = DISABLED
1048          * for each add endpoint ctx flag:
1049          *   cp(ep-in, ep-out)
1050          *   ep->state = RUNNING
1051          * for each drop+add endpoint flag:
1052          *   reset ep resources
1053          *   cp(ep-in, ep-out)
1054          *   ep->state = RUNNING
1055          * if input->DisabledCtx[2-31] < 30: (at least 1 ep not disabled)
1056          *   slot->state = configured
1057          */
1058
1059         input_ctx = XHCI_GADDR(sc, trb->qwTrb0 & ~0xFUL);
1060         dev_ctx = dev->dev_ctx;
1061         DPRINTF(("pci_xhci: config_ep inputctx: D:x%08x A:x%08x 7:x%08x",
1062                 input_ctx->ctx_input.dwInCtx0, input_ctx->ctx_input.dwInCtx1,
1063                 input_ctx->ctx_input.dwInCtx7));
1064
1065         for (i = 2; i <= 31; i++) {
1066                 ep_ctx = &dev_ctx->ctx_ep[i];
1067
1068                 if (input_ctx->ctx_input.dwInCtx0 &
1069                     XHCI_INCTX_0_DROP_MASK(i)) {
1070                         DPRINTF((" config ep - dropping ep %d", i));
1071                         pci_xhci_disable_ep(dev, i);
1072                 }
1073
1074                 if (input_ctx->ctx_input.dwInCtx1 &
1075                     XHCI_INCTX_1_ADD_MASK(i)) {
1076                         iep_ctx = &input_ctx->ctx_ep[i];
1077
1078                         DPRINTF((" enable ep[%d]  %08x %08x %016lx %08x",
1079                            i, iep_ctx->dwEpCtx0, iep_ctx->dwEpCtx1,
1080                            iep_ctx->qwEpCtx2, iep_ctx->dwEpCtx4));
1081
1082                         memcpy(ep_ctx, iep_ctx, sizeof(struct xhci_endp_ctx));
1083
1084                         pci_xhci_init_ep(dev, i);
1085
1086                         /* ep state */
1087                         ep_ctx->dwEpCtx0 = FIELD_REPLACE(
1088                             ep_ctx->dwEpCtx0, XHCI_ST_EPCTX_RUNNING, 0x7, 0);
1089                 }
1090         }
1091
1092         /* slot state to configured */
1093         dev_ctx->ctx_slot.dwSctx3 = FIELD_REPLACE(
1094             dev_ctx->ctx_slot.dwSctx3, XHCI_ST_SLCTX_CONFIGURED, 0x1F, 27);
1095         dev_ctx->ctx_slot.dwSctx0 = FIELD_COPY(
1096             dev_ctx->ctx_slot.dwSctx0, input_ctx->ctx_slot.dwSctx0, 0x1F, 27);
1097         dev->dev_slotstate = XHCI_ST_CONFIGURED;
1098
1099         DPRINTF(("EP configured; slot %u [0]=0x%08x [1]=0x%08x [2]=0x%08x "
1100                  "[3]=0x%08x",
1101             slot, dev_ctx->ctx_slot.dwSctx0, dev_ctx->ctx_slot.dwSctx1,
1102             dev_ctx->ctx_slot.dwSctx2, dev_ctx->ctx_slot.dwSctx3));
1103
1104 done:
1105         return (cmderr);
1106 }
1107
1108 static uint32_t
1109 pci_xhci_cmd_reset_ep(struct pci_xhci_softc *sc, uint32_t slot,
1110     struct xhci_trb *trb)
1111 {
1112         struct pci_xhci_dev_emu *dev;
1113         struct pci_xhci_dev_ep *devep;
1114         struct xhci_dev_ctx     *dev_ctx;
1115         struct xhci_endp_ctx    *ep_ctx;
1116         uint32_t        cmderr, epid;
1117         uint32_t        type;
1118
1119         epid = XHCI_TRB_3_EP_GET(trb->dwTrb3);
1120
1121         DPRINTF(("pci_xhci: reset ep %u: slot %u", epid, slot));
1122
1123         cmderr = XHCI_TRB_ERROR_SUCCESS;
1124
1125         type = XHCI_TRB_3_TYPE_GET(trb->dwTrb3);
1126
1127         dev = XHCI_SLOTDEV_PTR(sc, slot);
1128         assert(dev != NULL);
1129
1130         if (type == XHCI_TRB_TYPE_STOP_EP &&
1131             (trb->dwTrb3 & XHCI_TRB_3_SUSP_EP_BIT) != 0) {
1132                 /* XXX suspend endpoint for 10ms */
1133         }
1134
1135         if (epid < 1 || epid > 31) {
1136                 DPRINTF(("pci_xhci: reset ep: invalid epid %u", epid));
1137                 cmderr = XHCI_TRB_ERROR_TRB;
1138                 goto done;
1139         }
1140
1141         devep = &dev->eps[epid];
1142         if (devep->ep_xfer != NULL)
1143                 USB_DATA_XFER_RESET(devep->ep_xfer);
1144
1145         dev_ctx = dev->dev_ctx;
1146         assert(dev_ctx != NULL);
1147
1148         ep_ctx = &dev_ctx->ctx_ep[epid];
1149
1150         ep_ctx->dwEpCtx0 = (ep_ctx->dwEpCtx0 & ~0x7) | XHCI_ST_EPCTX_STOPPED;
1151
1152         if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) == 0)
1153                 ep_ctx->qwEpCtx2 = devep->ep_ringaddr | devep->ep_ccs;
1154
1155         DPRINTF(("pci_xhci: reset ep[%u] %08x %08x %016lx %08x",
1156                 epid, ep_ctx->dwEpCtx0, ep_ctx->dwEpCtx1, ep_ctx->qwEpCtx2,
1157                 ep_ctx->dwEpCtx4));
1158
1159         if (type == XHCI_TRB_TYPE_RESET_EP &&
1160             (dev->dev_ue->ue_reset == NULL ||
1161             dev->dev_ue->ue_reset(dev->dev_sc) < 0)) {
1162                 cmderr = XHCI_TRB_ERROR_ENDP_NOT_ON;
1163                 goto done;
1164         }
1165
1166 done:
1167         return (cmderr);
1168 }
1169
1170
1171 static uint32_t
1172 pci_xhci_find_stream(struct pci_xhci_softc *sc, struct xhci_endp_ctx *ep,
1173     uint32_t streamid, struct xhci_stream_ctx **osctx)
1174 {
1175         struct xhci_stream_ctx *sctx;
1176         uint32_t        maxpstreams;
1177
1178         maxpstreams = XHCI_EPCTX_0_MAXP_STREAMS_GET(ep->dwEpCtx0);
1179         if (maxpstreams == 0)
1180                 return (XHCI_TRB_ERROR_TRB);
1181
1182         if (maxpstreams > XHCI_STREAMS_MAX)
1183                 return (XHCI_TRB_ERROR_INVALID_SID);
1184
1185         if (XHCI_EPCTX_0_LSA_GET(ep->dwEpCtx0) == 0) {
1186                 DPRINTF(("pci_xhci: find_stream; LSA bit not set"));
1187                 return (XHCI_TRB_ERROR_INVALID_SID);
1188         }
1189
1190         /* only support primary stream */
1191         if (streamid > maxpstreams)
1192                 return (XHCI_TRB_ERROR_STREAM_TYPE);
1193
1194         sctx = XHCI_GADDR(sc, ep->qwEpCtx2 & ~0xFUL) + streamid;
1195         if (!XHCI_SCTX_0_SCT_GET(sctx->qwSctx0))
1196                 return (XHCI_TRB_ERROR_STREAM_TYPE);
1197
1198         *osctx = sctx;
1199
1200         return (XHCI_TRB_ERROR_SUCCESS);
1201 }
1202
1203
1204 static uint32_t
1205 pci_xhci_cmd_set_tr(struct pci_xhci_softc *sc, uint32_t slot,
1206     struct xhci_trb *trb)
1207 {
1208         struct pci_xhci_dev_emu *dev;
1209         struct pci_xhci_dev_ep  *devep;
1210         struct xhci_dev_ctx     *dev_ctx;
1211         struct xhci_endp_ctx    *ep_ctx;
1212         uint32_t        cmderr, epid;
1213         uint32_t        streamid;
1214
1215         cmderr = XHCI_TRB_ERROR_SUCCESS;
1216
1217         dev = XHCI_SLOTDEV_PTR(sc, slot);
1218         assert(dev != NULL);
1219
1220         DPRINTF(("pci_xhci set_tr: new-tr x%016lx, SCT %u DCS %u",
1221                  (trb->qwTrb0 & ~0xF),  (uint32_t)((trb->qwTrb0 >> 1) & 0x7),
1222                  (uint32_t)(trb->qwTrb0 & 0x1)));
1223         DPRINTF(("                 stream-id %u, slot %u, epid %u, C %u",
1224                  (trb->dwTrb2 >> 16) & 0xFFFF,
1225                  XHCI_TRB_3_SLOT_GET(trb->dwTrb3),
1226                  XHCI_TRB_3_EP_GET(trb->dwTrb3), trb->dwTrb3 & 0x1));
1227
1228         epid = XHCI_TRB_3_EP_GET(trb->dwTrb3);
1229         if (epid < 1 || epid > 31) {
1230                 DPRINTF(("pci_xhci: set_tr_deq: invalid epid %u", epid));
1231                 cmderr = XHCI_TRB_ERROR_TRB;
1232                 goto done;
1233         }
1234
1235         dev_ctx = dev->dev_ctx;
1236         assert(dev_ctx != NULL);
1237
1238         ep_ctx = &dev_ctx->ctx_ep[epid];
1239         devep = &dev->eps[epid];
1240
1241         switch (XHCI_EPCTX_0_EPSTATE_GET(ep_ctx->dwEpCtx0)) {
1242         case XHCI_ST_EPCTX_STOPPED:
1243         case XHCI_ST_EPCTX_ERROR:
1244                 break;
1245         default:
1246                 DPRINTF(("pci_xhci cmd set_tr invalid state %x",
1247                         XHCI_EPCTX_0_EPSTATE_GET(ep_ctx->dwEpCtx0)));
1248                 cmderr = XHCI_TRB_ERROR_CONTEXT_STATE;
1249                 goto done;
1250         }
1251
1252         streamid = XHCI_TRB_2_STREAM_GET(trb->dwTrb2);
1253         if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) > 0) {
1254                 struct xhci_stream_ctx *sctx;
1255
1256                 sctx = NULL;
1257                 cmderr = pci_xhci_find_stream(sc, ep_ctx, streamid, &sctx);
1258                 if (sctx != NULL) {
1259                         assert(devep->ep_sctx != NULL);
1260                         
1261                         devep->ep_sctx[streamid].qwSctx0 = trb->qwTrb0;
1262                         devep->ep_sctx_trbs[streamid].ringaddr =
1263                             trb->qwTrb0 & ~0xF;
1264                         devep->ep_sctx_trbs[streamid].ccs =
1265                             XHCI_EPCTX_2_DCS_GET(trb->qwTrb0);
1266                 }
1267         } else {
1268                 if (streamid != 0) {
1269                         DPRINTF(("pci_xhci cmd set_tr streamid %x != 0",
1270                                 streamid));
1271                 }
1272                 ep_ctx->qwEpCtx2 = trb->qwTrb0 & ~0xFUL;
1273                 devep->ep_ringaddr = ep_ctx->qwEpCtx2 & ~0xFUL;
1274                 devep->ep_ccs = trb->qwTrb0 & 0x1;
1275                 devep->ep_tr = XHCI_GADDR(sc, devep->ep_ringaddr);
1276
1277                 DPRINTF(("pci_xhci set_tr first TRB:"));
1278                 pci_xhci_dump_trb(devep->ep_tr);
1279         }
1280         ep_ctx->dwEpCtx0 = (ep_ctx->dwEpCtx0 & ~0x7) | XHCI_ST_EPCTX_STOPPED;
1281
1282 done:
1283         return (cmderr);
1284 }
1285
1286 static uint32_t
1287 pci_xhci_cmd_eval_ctx(struct pci_xhci_softc *sc, uint32_t slot,
1288     struct xhci_trb *trb)
1289 {
1290         struct xhci_input_dev_ctx *input_ctx;
1291         struct xhci_slot_ctx      *islot_ctx;
1292         struct xhci_dev_ctx       *dev_ctx;
1293         struct xhci_endp_ctx      *ep0_ctx;
1294         uint32_t cmderr;
1295
1296         input_ctx = XHCI_GADDR(sc, trb->qwTrb0 & ~0xFUL);
1297         islot_ctx = &input_ctx->ctx_slot;
1298         ep0_ctx = &input_ctx->ctx_ep[1];
1299
1300         cmderr = XHCI_TRB_ERROR_SUCCESS;
1301         DPRINTF(("pci_xhci: eval ctx, input ctl: D 0x%08x A 0x%08x,",
1302                 input_ctx->ctx_input.dwInCtx0, input_ctx->ctx_input.dwInCtx1));
1303         DPRINTF(("          slot %08x %08x %08x %08x",
1304                 islot_ctx->dwSctx0, islot_ctx->dwSctx1,
1305                 islot_ctx->dwSctx2, islot_ctx->dwSctx3));
1306         DPRINTF(("          ep0  %08x %08x %016lx %08x",
1307                 ep0_ctx->dwEpCtx0, ep0_ctx->dwEpCtx1, ep0_ctx->qwEpCtx2,
1308                 ep0_ctx->dwEpCtx4));
1309
1310         /* this command expects drop-ctx=0 & add-ctx=slot+ep0 */
1311         if ((input_ctx->ctx_input.dwInCtx0 != 0) ||
1312             (input_ctx->ctx_input.dwInCtx1 & 0x03) == 0) {
1313                 DPRINTF(("pci_xhci: eval ctx, input ctl invalid"));
1314                 cmderr = XHCI_TRB_ERROR_TRB;
1315                 goto done;
1316         }
1317
1318         /* assign address to slot; in this emulation, slot_id = address */
1319         dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
1320
1321         DPRINTF(("pci_xhci: eval ctx, dev ctx"));
1322         DPRINTF(("          slot %08x %08x %08x %08x",
1323                 dev_ctx->ctx_slot.dwSctx0, dev_ctx->ctx_slot.dwSctx1,
1324                 dev_ctx->ctx_slot.dwSctx2, dev_ctx->ctx_slot.dwSctx3));
1325
1326         if (input_ctx->ctx_input.dwInCtx1 & 0x01) {     /* slot ctx */
1327                 /* set max exit latency */
1328                 dev_ctx->ctx_slot.dwSctx1 = FIELD_COPY(
1329                     dev_ctx->ctx_slot.dwSctx1, input_ctx->ctx_slot.dwSctx1,
1330                     0xFFFF, 0);
1331
1332                 /* set interrupter target */
1333                 dev_ctx->ctx_slot.dwSctx2 = FIELD_COPY(
1334                     dev_ctx->ctx_slot.dwSctx2, input_ctx->ctx_slot.dwSctx2,
1335                     0x3FF, 22);
1336         }
1337         if (input_ctx->ctx_input.dwInCtx1 & 0x02) {     /* control ctx */
1338                 /* set max packet size */
1339                 dev_ctx->ctx_ep[1].dwEpCtx1 = FIELD_COPY(
1340                     dev_ctx->ctx_ep[1].dwEpCtx1, ep0_ctx->dwEpCtx1,
1341                     0xFFFF, 16);
1342
1343                 ep0_ctx = &dev_ctx->ctx_ep[1];
1344         }
1345
1346         DPRINTF(("pci_xhci: eval ctx, output ctx"));
1347         DPRINTF(("          slot %08x %08x %08x %08x",
1348                 dev_ctx->ctx_slot.dwSctx0, dev_ctx->ctx_slot.dwSctx1,
1349                 dev_ctx->ctx_slot.dwSctx2, dev_ctx->ctx_slot.dwSctx3));
1350         DPRINTF(("          ep0  %08x %08x %016lx %08x",
1351                 ep0_ctx->dwEpCtx0, ep0_ctx->dwEpCtx1, ep0_ctx->qwEpCtx2,
1352                 ep0_ctx->dwEpCtx4));
1353
1354 done:
1355         return (cmderr);
1356 }
1357
1358 static int
1359 pci_xhci_complete_commands(struct pci_xhci_softc *sc)
1360 {
1361         struct xhci_trb evtrb;
1362         struct xhci_trb *trb;
1363         uint64_t        crcr;
1364         uint32_t        ccs;            /* cycle state (XHCI 4.9.2) */
1365         uint32_t        type;
1366         uint32_t        slot;
1367         uint32_t        cmderr;
1368         int             error;
1369
1370         error = 0;
1371         sc->opregs.crcr |= XHCI_CRCR_LO_CRR;
1372
1373         trb = sc->opregs.cr_p;
1374         ccs = sc->opregs.crcr & XHCI_CRCR_LO_RCS;
1375         crcr = sc->opregs.crcr & ~0xF;
1376
1377         while (1) {
1378                 sc->opregs.cr_p = trb;
1379         
1380                 type = XHCI_TRB_3_TYPE_GET(trb->dwTrb3);
1381
1382                 if ((trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT) !=
1383                     (ccs & XHCI_TRB_3_CYCLE_BIT))
1384                         break;
1385
1386                 DPRINTF(("pci_xhci: cmd type 0x%x, Trb0 x%016lx dwTrb2 x%08x"
1387                         " dwTrb3 x%08x, TRB_CYCLE %u/ccs %u",
1388                         type, trb->qwTrb0, trb->dwTrb2, trb->dwTrb3,
1389                         trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT, ccs));
1390
1391                 cmderr = XHCI_TRB_ERROR_SUCCESS;
1392                 evtrb.dwTrb2 = 0;
1393                 evtrb.dwTrb3 = (ccs & XHCI_TRB_3_CYCLE_BIT) |
1394                       XHCI_TRB_3_TYPE_SET(XHCI_TRB_EVENT_CMD_COMPLETE);
1395                 slot = 0;
1396
1397                 switch (type) {
1398                 case XHCI_TRB_TYPE_LINK:                        /* 0x06 */
1399                         if (trb->dwTrb3 & XHCI_TRB_3_TC_BIT)
1400                                 ccs ^= XHCI_CRCR_LO_RCS;
1401                         break;
1402
1403                 case XHCI_TRB_TYPE_ENABLE_SLOT:                 /* 0x09 */
1404                         cmderr = pci_xhci_cmd_enable_slot(sc, &slot);
1405                         break;
1406
1407                 case XHCI_TRB_TYPE_DISABLE_SLOT:                /* 0x0A */
1408                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1409                         cmderr = pci_xhci_cmd_disable_slot(sc, slot);
1410                         break;
1411
1412                 case XHCI_TRB_TYPE_ADDRESS_DEVICE:              /* 0x0B */
1413                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1414                         cmderr = pci_xhci_cmd_address_device(sc, slot, trb);
1415                         break;
1416
1417                 case XHCI_TRB_TYPE_CONFIGURE_EP:                /* 0x0C */
1418                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1419                         cmderr = pci_xhci_cmd_config_ep(sc, slot, trb);
1420                         break;
1421
1422                 case XHCI_TRB_TYPE_EVALUATE_CTX:                /* 0x0D */
1423                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1424                         cmderr = pci_xhci_cmd_eval_ctx(sc, slot, trb);
1425                         break;
1426
1427                 case XHCI_TRB_TYPE_RESET_EP:                    /* 0x0E */
1428                         DPRINTF(("Reset Endpoint on slot %d", slot));
1429                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1430                         cmderr = pci_xhci_cmd_reset_ep(sc, slot, trb);
1431                         break;
1432
1433                 case XHCI_TRB_TYPE_STOP_EP:                     /* 0x0F */
1434                         DPRINTF(("Stop Endpoint on slot %d", slot));
1435                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1436                         cmderr = pci_xhci_cmd_reset_ep(sc, slot, trb);
1437                         break;
1438
1439                 case XHCI_TRB_TYPE_SET_TR_DEQUEUE:              /* 0x10 */
1440                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1441                         cmderr = pci_xhci_cmd_set_tr(sc, slot, trb);
1442                         break;
1443
1444                 case XHCI_TRB_TYPE_RESET_DEVICE:                /* 0x11 */
1445                         slot = XHCI_TRB_3_SLOT_GET(trb->dwTrb3);
1446                         cmderr = pci_xhci_cmd_reset_device(sc, slot);
1447                         break;
1448
1449                 case XHCI_TRB_TYPE_FORCE_EVENT:                 /* 0x12 */
1450                         /* TODO: */
1451                         break;
1452
1453                 case XHCI_TRB_TYPE_NEGOTIATE_BW:                /* 0x13 */
1454                         break;
1455
1456                 case XHCI_TRB_TYPE_SET_LATENCY_TOL:             /* 0x14 */
1457                         break;
1458
1459                 case XHCI_TRB_TYPE_GET_PORT_BW:                 /* 0x15 */
1460                         break;
1461
1462                 case XHCI_TRB_TYPE_FORCE_HEADER:                /* 0x16 */
1463                         break;
1464
1465                 case XHCI_TRB_TYPE_NOOP_CMD:                    /* 0x17 */
1466                         break;
1467
1468                 default:
1469                         DPRINTF(("pci_xhci: unsupported cmd %x", type));
1470                         break;
1471                 }
1472
1473                 if (type != XHCI_TRB_TYPE_LINK) {
1474                         /* 
1475                          * insert command completion event and assert intr
1476                          */
1477                         evtrb.qwTrb0 = crcr;
1478                         evtrb.dwTrb2 |= XHCI_TRB_2_ERROR_SET(cmderr);
1479                         evtrb.dwTrb3 |= XHCI_TRB_3_SLOT_SET(slot);
1480                         DPRINTF(("pci_xhci: command 0x%x result: 0x%x",
1481                                 type, cmderr));
1482                         pci_xhci_insert_event(sc, &evtrb, 1);
1483                 }
1484
1485                 trb = pci_xhci_trb_next(sc, trb, &crcr);
1486         }
1487
1488         sc->opregs.crcr = crcr | (sc->opregs.crcr & XHCI_CRCR_LO_CA) | ccs;
1489         sc->opregs.crcr &= ~XHCI_CRCR_LO_CRR;
1490         return (error);
1491 }
1492
1493 static void
1494 pci_xhci_dump_trb(struct xhci_trb *trb)
1495 {
1496         static const char *trbtypes[] = {
1497                 "RESERVED",
1498                 "NORMAL",
1499                 "SETUP_STAGE",
1500                 "DATA_STAGE",
1501                 "STATUS_STAGE",
1502                 "ISOCH",
1503                 "LINK",
1504                 "EVENT_DATA",
1505                 "NOOP",
1506                 "ENABLE_SLOT",
1507                 "DISABLE_SLOT",
1508                 "ADDRESS_DEVICE",
1509                 "CONFIGURE_EP",
1510                 "EVALUATE_CTX",
1511                 "RESET_EP",
1512                 "STOP_EP",
1513                 "SET_TR_DEQUEUE",
1514                 "RESET_DEVICE",
1515                 "FORCE_EVENT",
1516                 "NEGOTIATE_BW",
1517                 "SET_LATENCY_TOL",
1518                 "GET_PORT_BW",
1519                 "FORCE_HEADER",
1520                 "NOOP_CMD"
1521         };
1522         uint32_t type;
1523
1524         type = XHCI_TRB_3_TYPE_GET(trb->dwTrb3);
1525         DPRINTF(("pci_xhci: trb[@%p] type x%02x %s 0:x%016lx 2:x%08x 3:x%08x",
1526                  trb, type,
1527                  type <= XHCI_TRB_TYPE_NOOP_CMD ? trbtypes[type] : "INVALID",
1528                  trb->qwTrb0, trb->dwTrb2, trb->dwTrb3));
1529 }
1530
1531 static int
1532 pci_xhci_xfer_complete(struct pci_xhci_softc *sc, struct usb_data_xfer *xfer,
1533      uint32_t slot, uint32_t epid, int *do_intr)
1534 {
1535         struct pci_xhci_dev_emu *dev;
1536         struct pci_xhci_dev_ep  *devep;
1537         struct xhci_dev_ctx     *dev_ctx;
1538         struct xhci_endp_ctx    *ep_ctx;
1539         struct xhci_trb         *trb;
1540         struct xhci_trb         evtrb;
1541         uint32_t trbflags;
1542         uint32_t edtla;
1543         int i, err;
1544
1545         dev = XHCI_SLOTDEV_PTR(sc, slot);
1546         devep = &dev->eps[epid];
1547         dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
1548
1549         assert(dev_ctx != NULL);
1550
1551         ep_ctx = &dev_ctx->ctx_ep[epid];
1552
1553         err = XHCI_TRB_ERROR_SUCCESS;
1554         *do_intr = 0;
1555         edtla = 0;
1556
1557         /* go through list of TRBs and insert event(s) */
1558         for (i = xfer->head; xfer->ndata > 0; ) {
1559                 evtrb.qwTrb0 = (uint64_t)xfer->data[i].hci_data;
1560                 trb = XHCI_GADDR(sc, evtrb.qwTrb0);
1561                 trbflags = trb->dwTrb3;
1562
1563                 DPRINTF(("pci_xhci: xfer[%d] done?%u:%d trb %x %016lx %x "
1564                          "(err %d) IOC?%d",
1565                      i, xfer->data[i].processed, xfer->data[i].blen,
1566                      XHCI_TRB_3_TYPE_GET(trbflags), evtrb.qwTrb0,
1567                      trbflags, err,
1568                      trb->dwTrb3 & XHCI_TRB_3_IOC_BIT ? 1 : 0));
1569
1570                 if (!xfer->data[i].processed) {
1571                         xfer->head = i;
1572                         break;
1573                 }
1574
1575                 xfer->ndata--;
1576                 edtla += xfer->data[i].bdone;
1577
1578                 trb->dwTrb3 = (trb->dwTrb3 & ~0x1) | (xfer->data[i].ccs);
1579
1580                 pci_xhci_update_ep_ring(sc, dev, devep, ep_ctx,
1581                     xfer->data[i].streamid, xfer->data[i].trbnext,
1582                     xfer->data[i].ccs);
1583
1584                 /* Only interrupt if IOC or short packet */
1585                 if (!(trb->dwTrb3 & XHCI_TRB_3_IOC_BIT) &&
1586                     !((err == XHCI_TRB_ERROR_SHORT_PKT) &&
1587                       (trb->dwTrb3 & XHCI_TRB_3_ISP_BIT))) {
1588
1589                         i = (i + 1) % USB_MAX_XFER_BLOCKS;
1590                         continue;
1591                 }
1592
1593                 evtrb.dwTrb2 = XHCI_TRB_2_ERROR_SET(err) |
1594                                XHCI_TRB_2_REM_SET(xfer->data[i].blen);
1595
1596                 evtrb.dwTrb3 = XHCI_TRB_3_TYPE_SET(XHCI_TRB_EVENT_TRANSFER) |
1597                     XHCI_TRB_3_SLOT_SET(slot) | XHCI_TRB_3_EP_SET(epid);
1598
1599                 if (XHCI_TRB_3_TYPE_GET(trbflags) == XHCI_TRB_TYPE_EVENT_DATA) {
1600                         DPRINTF(("pci_xhci EVENT_DATA edtla %u", edtla));
1601                         evtrb.qwTrb0 = trb->qwTrb0;
1602                         evtrb.dwTrb2 = (edtla & 0xFFFFF) | 
1603                                  XHCI_TRB_2_ERROR_SET(err);
1604                         evtrb.dwTrb3 |= XHCI_TRB_3_ED_BIT;
1605                         edtla = 0;
1606                 }
1607
1608                 *do_intr = 1;
1609
1610                 err = pci_xhci_insert_event(sc, &evtrb, 0);
1611                 if (err != XHCI_TRB_ERROR_SUCCESS) {
1612                         break;
1613                 }
1614
1615                 i = (i + 1) % USB_MAX_XFER_BLOCKS;
1616         }
1617
1618         return (err);
1619 }
1620
1621 static void
1622 pci_xhci_update_ep_ring(struct pci_xhci_softc *sc, struct pci_xhci_dev_emu *dev,
1623     struct pci_xhci_dev_ep *devep, struct xhci_endp_ctx *ep_ctx,
1624     uint32_t streamid, uint64_t ringaddr, int ccs)
1625 {
1626
1627         if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) != 0) {
1628                 devep->ep_sctx[streamid].qwSctx0 = (ringaddr & ~0xFUL) |
1629                                                    (ccs & 0x1);
1630
1631                 devep->ep_sctx_trbs[streamid].ringaddr = ringaddr & ~0xFUL;
1632                 devep->ep_sctx_trbs[streamid].ccs = ccs & 0x1;
1633                 ep_ctx->qwEpCtx2 = (ep_ctx->qwEpCtx2 & ~0x1) | (ccs & 0x1);
1634
1635                 DPRINTF(("xhci update ep-ring stream %d, addr %lx",
1636                     streamid, devep->ep_sctx[streamid].qwSctx0));
1637         } else {
1638                 devep->ep_ringaddr = ringaddr & ~0xFUL;
1639                 devep->ep_ccs = ccs & 0x1;
1640                 devep->ep_tr = XHCI_GADDR(sc, ringaddr & ~0xFUL);
1641                 ep_ctx->qwEpCtx2 = (ringaddr & ~0xFUL) | (ccs & 0x1);
1642
1643                 DPRINTF(("xhci update ep-ring, addr %lx",
1644                     (devep->ep_ringaddr | devep->ep_ccs)));
1645         }
1646 }
1647
1648 /*
1649  * Outstanding transfer still in progress (device NAK'd earlier) so retry
1650  * the transfer again to see if it succeeds.
1651  */
1652 static int
1653 pci_xhci_try_usb_xfer(struct pci_xhci_softc *sc,
1654     struct pci_xhci_dev_emu *dev, struct pci_xhci_dev_ep *devep,
1655     struct xhci_endp_ctx *ep_ctx, uint32_t slot, uint32_t epid)
1656 {
1657         struct usb_data_xfer *xfer;
1658         int             err;
1659         int             do_intr;
1660
1661         ep_ctx->dwEpCtx0 = FIELD_REPLACE(
1662                     ep_ctx->dwEpCtx0, XHCI_ST_EPCTX_RUNNING, 0x7, 0);
1663
1664         err = 0;
1665         do_intr = 0;
1666
1667         xfer = devep->ep_xfer;
1668         USB_DATA_XFER_LOCK(xfer);
1669
1670         /* outstanding requests queued up */
1671         if (dev->dev_ue->ue_data != NULL) {
1672                 err = dev->dev_ue->ue_data(dev->dev_sc, xfer,
1673                             epid & 0x1 ? USB_XFER_IN : USB_XFER_OUT, epid/2);
1674                 if (err == USB_ERR_CANCELLED) {
1675                         if (USB_DATA_GET_ERRCODE(&xfer->data[xfer->head]) ==
1676                             USB_NAK)
1677                                 err = XHCI_TRB_ERROR_SUCCESS;
1678                 } else {
1679                         err = pci_xhci_xfer_complete(sc, xfer, slot, epid,
1680                                                      &do_intr);
1681                         if (err == XHCI_TRB_ERROR_SUCCESS && do_intr) {
1682                                 pci_xhci_assert_interrupt(sc);
1683                         }
1684
1685
1686                         /* XXX should not do it if error? */
1687                         USB_DATA_XFER_RESET(xfer);
1688                 }
1689         }
1690
1691         USB_DATA_XFER_UNLOCK(xfer);
1692
1693
1694         return (err);
1695 }
1696
1697
1698 static int
1699 pci_xhci_handle_transfer(struct pci_xhci_softc *sc,
1700     struct pci_xhci_dev_emu *dev, struct pci_xhci_dev_ep *devep,
1701     struct xhci_endp_ctx *ep_ctx, struct xhci_trb *trb, uint32_t slot,
1702     uint32_t epid, uint64_t addr, uint32_t ccs, uint32_t streamid)
1703 {
1704         struct xhci_trb *setup_trb;
1705         struct usb_data_xfer *xfer;
1706         struct usb_data_xfer_block *xfer_block;
1707         uint64_t        val;
1708         uint32_t        trbflags;
1709         int             do_intr, err;
1710         int             do_retry;
1711
1712         ep_ctx->dwEpCtx0 = FIELD_REPLACE(ep_ctx->dwEpCtx0,
1713                                          XHCI_ST_EPCTX_RUNNING, 0x7, 0);
1714
1715         xfer = devep->ep_xfer;
1716         USB_DATA_XFER_LOCK(xfer);
1717
1718         DPRINTF(("pci_xhci handle_transfer slot %u", slot));
1719
1720 retry:
1721         err = 0;
1722         do_retry = 0;
1723         do_intr = 0;
1724         setup_trb = NULL;
1725
1726         while (1) {
1727                 pci_xhci_dump_trb(trb);
1728
1729                 trbflags = trb->dwTrb3;
1730
1731                 if (XHCI_TRB_3_TYPE_GET(trbflags) != XHCI_TRB_TYPE_LINK &&
1732                     (trbflags & XHCI_TRB_3_CYCLE_BIT) !=
1733                     (ccs & XHCI_TRB_3_CYCLE_BIT)) {
1734                         DPRINTF(("Cycle-bit changed trbflags %x, ccs %x",
1735                             trbflags & XHCI_TRB_3_CYCLE_BIT, ccs));
1736                         break;
1737                 }
1738
1739                 xfer_block = NULL;
1740
1741                 switch (XHCI_TRB_3_TYPE_GET(trbflags)) {
1742                 case XHCI_TRB_TYPE_LINK:
1743                         if (trb->dwTrb3 & XHCI_TRB_3_TC_BIT)
1744                                 ccs ^= 0x1;
1745
1746                         xfer_block = usb_data_xfer_append(xfer, NULL, 0,
1747                                                           (void *)addr, ccs);
1748                         xfer_block->processed = 1;
1749                         break;
1750
1751                 case XHCI_TRB_TYPE_SETUP_STAGE:
1752                         if ((trbflags & XHCI_TRB_3_IDT_BIT) == 0 ||
1753                             XHCI_TRB_2_BYTES_GET(trb->dwTrb2) != 8) {
1754                                 DPRINTF(("pci_xhci: invalid setup trb"));
1755                                 err = XHCI_TRB_ERROR_TRB;
1756                                 goto errout;
1757                         }
1758                         setup_trb = trb;
1759
1760                         val = trb->qwTrb0;
1761                         if (!xfer->ureq)
1762                                 xfer->ureq = malloc(
1763                                            sizeof(struct usb_device_request));
1764                         memcpy(xfer->ureq, &val,
1765                                sizeof(struct usb_device_request));
1766
1767                         xfer_block = usb_data_xfer_append(xfer, NULL, 0,
1768                                                           (void *)addr, ccs);
1769                         xfer_block->processed = 1;
1770                         break;
1771
1772                 case XHCI_TRB_TYPE_NORMAL:
1773                 case XHCI_TRB_TYPE_ISOCH:
1774                         if (setup_trb != NULL) {
1775                                 DPRINTF(("pci_xhci: trb not supposed to be in "
1776                                          "ctl scope"));
1777                                 err = XHCI_TRB_ERROR_TRB;
1778                                 goto errout;
1779                         }
1780                         /* fall through */
1781
1782                 case XHCI_TRB_TYPE_DATA_STAGE:
1783                         xfer_block = usb_data_xfer_append(xfer,
1784                              (void *)(trbflags & XHCI_TRB_3_IDT_BIT ?
1785                                  &trb->qwTrb0 : XHCI_GADDR(sc, trb->qwTrb0)),
1786                              trb->dwTrb2 & 0x1FFFF, (void *)addr, ccs);
1787                         break;
1788
1789                 case XHCI_TRB_TYPE_STATUS_STAGE:
1790                         xfer_block = usb_data_xfer_append(xfer, NULL, 0,
1791                                                           (void *)addr, ccs);
1792                         break;
1793
1794                 case XHCI_TRB_TYPE_NOOP:
1795                         xfer_block = usb_data_xfer_append(xfer, NULL, 0,
1796                                                           (void *)addr, ccs);
1797                         xfer_block->processed = 1;
1798                         break;
1799
1800                 case XHCI_TRB_TYPE_EVENT_DATA:
1801                         xfer_block = usb_data_xfer_append(xfer, NULL, 0,
1802                                                           (void *)addr, ccs);
1803                         if ((epid > 1) && (trbflags & XHCI_TRB_3_IOC_BIT)) {
1804                                 xfer_block->processed = 1;
1805                         }
1806                         break;
1807
1808                 default:
1809                         DPRINTF(("pci_xhci: handle xfer unexpected trb type "
1810                                  "0x%x",
1811                                  XHCI_TRB_3_TYPE_GET(trbflags)));
1812                         err = XHCI_TRB_ERROR_TRB;
1813                         goto errout;
1814                 }
1815
1816                 trb = pci_xhci_trb_next(sc, trb, &addr);
1817
1818                 DPRINTF(("pci_xhci: next trb: 0x%lx", (uint64_t)trb));
1819
1820                 if (xfer_block) {
1821                         xfer_block->trbnext = addr;
1822                         xfer_block->streamid = streamid;
1823                 }
1824
1825                 if (!setup_trb && !(trbflags & XHCI_TRB_3_CHAIN_BIT) &&
1826                     XHCI_TRB_3_TYPE_GET(trbflags) != XHCI_TRB_TYPE_LINK) {
1827                         break;
1828                 }
1829
1830                 /* handle current batch that requires interrupt on complete */
1831                 if (trbflags & XHCI_TRB_3_IOC_BIT) {
1832                         DPRINTF(("pci_xhci: trb IOC bit set"));
1833                         if (epid == 1)
1834                                 do_retry = 1;
1835                         break;
1836                 }
1837         }
1838
1839         DPRINTF(("pci_xhci[%d]: xfer->ndata %u", __LINE__, xfer->ndata));
1840
1841         if (xfer->ndata <= 0)
1842                 goto errout;
1843
1844         if (epid == 1) {
1845                 err = USB_ERR_NOT_STARTED;
1846                 if (dev->dev_ue->ue_request != NULL)
1847                         err = dev->dev_ue->ue_request(dev->dev_sc, xfer);
1848                 setup_trb = NULL;
1849         } else {
1850                 /* handle data transfer */
1851                 pci_xhci_try_usb_xfer(sc, dev, devep, ep_ctx, slot, epid);
1852                 err = XHCI_TRB_ERROR_SUCCESS;
1853                 goto errout;
1854         }
1855
1856         err = USB_TO_XHCI_ERR(err);
1857         if ((err == XHCI_TRB_ERROR_SUCCESS) ||
1858             (err == XHCI_TRB_ERROR_STALL) ||
1859             (err == XHCI_TRB_ERROR_SHORT_PKT)) {
1860                 err = pci_xhci_xfer_complete(sc, xfer, slot, epid, &do_intr);
1861                 if (err != XHCI_TRB_ERROR_SUCCESS)
1862                         do_retry = 0;
1863         }
1864
1865 errout:
1866         if (err == XHCI_TRB_ERROR_EV_RING_FULL)
1867                 DPRINTF(("pci_xhci[%d]: event ring full", __LINE__));
1868
1869         if (!do_retry)
1870                 USB_DATA_XFER_UNLOCK(xfer);
1871
1872         if (do_intr)
1873                 pci_xhci_assert_interrupt(sc);
1874
1875         if (do_retry) {
1876                 USB_DATA_XFER_RESET(xfer);
1877                 DPRINTF(("pci_xhci[%d]: retry:continuing with next TRBs",
1878                          __LINE__));
1879                 goto retry;
1880         }
1881
1882         if (epid == 1)
1883                 USB_DATA_XFER_RESET(xfer);
1884
1885         return (err);
1886 }
1887
1888 static void
1889 pci_xhci_device_doorbell(struct pci_xhci_softc *sc, uint32_t slot,
1890     uint32_t epid, uint32_t streamid)
1891 {
1892         struct pci_xhci_dev_emu *dev;
1893         struct pci_xhci_dev_ep  *devep;
1894         struct xhci_dev_ctx     *dev_ctx;
1895         struct xhci_endp_ctx    *ep_ctx;
1896         struct pci_xhci_trb_ring *sctx_tr;
1897         struct xhci_trb *trb;
1898         uint64_t        ringaddr;
1899         uint32_t        ccs;
1900
1901         DPRINTF(("pci_xhci doorbell slot %u epid %u stream %u",
1902             slot, epid, streamid));
1903
1904         if (slot == 0 || slot > sc->ndevices) {
1905                 DPRINTF(("pci_xhci: invalid doorbell slot %u", slot));
1906                 return;
1907         }
1908
1909         if (epid == 0 || epid >= XHCI_MAX_ENDPOINTS) {
1910                 DPRINTF(("pci_xhci: invalid endpoint %u", epid));
1911                 return;
1912         }
1913
1914         dev = XHCI_SLOTDEV_PTR(sc, slot);
1915         devep = &dev->eps[epid];
1916         dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
1917         if (!dev_ctx) {
1918                 return;
1919         }
1920         ep_ctx = &dev_ctx->ctx_ep[epid];
1921
1922         sctx_tr = NULL;
1923
1924         DPRINTF(("pci_xhci: device doorbell ep[%u] %08x %08x %016lx %08x",
1925                 epid, ep_ctx->dwEpCtx0, ep_ctx->dwEpCtx1, ep_ctx->qwEpCtx2,
1926                 ep_ctx->dwEpCtx4));
1927
1928         if (ep_ctx->qwEpCtx2 == 0)
1929                 return;
1930
1931         /* handle pending transfers */
1932         if (devep->ep_xfer->ndata > 0) {
1933                 pci_xhci_try_usb_xfer(sc, dev, devep, ep_ctx, slot, epid);
1934                 return;
1935         }
1936
1937         /* get next trb work item */
1938         if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) != 0) {
1939                 struct xhci_stream_ctx *sctx;
1940
1941                 /*
1942                  * Stream IDs of 0, 65535 (any stream), and 65534
1943                  * (prime) are invalid.
1944                  */
1945                 if (streamid == 0 || streamid == 65534 || streamid == 65535) {
1946                         DPRINTF(("pci_xhci: invalid stream %u", streamid));
1947                         return;
1948                 }
1949
1950                 sctx = NULL;
1951                 pci_xhci_find_stream(sc, ep_ctx, streamid, &sctx);
1952                 if (sctx == NULL) {
1953                         DPRINTF(("pci_xhci: invalid stream %u", streamid));
1954                         return;
1955                 }
1956                 sctx_tr = &devep->ep_sctx_trbs[streamid];
1957                 ringaddr = sctx_tr->ringaddr;
1958                 ccs = sctx_tr->ccs;
1959                 trb = XHCI_GADDR(sc, sctx_tr->ringaddr & ~0xFUL);
1960                 DPRINTF(("doorbell, stream %u, ccs %lx, trb ccs %x",
1961                         streamid, ep_ctx->qwEpCtx2 & XHCI_TRB_3_CYCLE_BIT,
1962                         trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT));
1963         } else {
1964                 if (streamid != 0) {
1965                         DPRINTF(("pci_xhci: invalid stream %u", streamid));
1966                         return;
1967                 }
1968                 ringaddr = devep->ep_ringaddr;
1969                 ccs = devep->ep_ccs;
1970                 trb = devep->ep_tr;
1971                 DPRINTF(("doorbell, ccs %lx, trb ccs %x",
1972                         ep_ctx->qwEpCtx2 & XHCI_TRB_3_CYCLE_BIT,
1973                         trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT));
1974         }
1975
1976         if (XHCI_TRB_3_TYPE_GET(trb->dwTrb3) == 0) {
1977                 DPRINTF(("pci_xhci: ring %lx trb[%lx] EP %u is RESERVED?",
1978                         ep_ctx->qwEpCtx2, devep->ep_ringaddr, epid));
1979                 return;
1980         }
1981
1982         pci_xhci_handle_transfer(sc, dev, devep, ep_ctx, trb, slot, epid,
1983                                  ringaddr, ccs, streamid);
1984 }
1985
1986 static void
1987 pci_xhci_dbregs_write(struct pci_xhci_softc *sc, uint64_t offset,
1988     uint64_t value)
1989 {
1990
1991         offset = (offset - sc->dboff) / sizeof(uint32_t);
1992
1993         DPRINTF(("pci_xhci: doorbell write offset 0x%lx: 0x%lx",
1994                 offset, value));
1995
1996         if (XHCI_HALTED(sc)) {
1997                 DPRINTF(("pci_xhci: controller halted"));
1998                 return;
1999         }
2000
2001         if (offset == 0)
2002                 pci_xhci_complete_commands(sc);
2003         else if (sc->portregs != NULL)
2004                 pci_xhci_device_doorbell(sc, offset,
2005                    XHCI_DB_TARGET_GET(value), XHCI_DB_SID_GET(value));
2006 }
2007
2008 static void
2009 pci_xhci_rtsregs_write(struct pci_xhci_softc *sc, uint64_t offset,
2010     uint64_t value)
2011 {
2012         struct pci_xhci_rtsregs *rts;
2013
2014         offset -= sc->rtsoff;
2015
2016         if (offset == 0) {
2017                 DPRINTF(("pci_xhci attempted write to MFINDEX"));
2018                 return;
2019         }
2020
2021         DPRINTF(("pci_xhci: runtime regs write offset 0x%lx: 0x%lx",
2022                 offset, value));
2023
2024         offset -= 0x20;         /* start of intrreg */
2025
2026         rts = &sc->rtsregs;
2027
2028         switch (offset) {
2029         case 0x00:
2030                 if (value & XHCI_IMAN_INTR_PEND)
2031                         rts->intrreg.iman &= ~XHCI_IMAN_INTR_PEND;
2032                 rts->intrreg.iman = (value & XHCI_IMAN_INTR_ENA) |
2033                                     (rts->intrreg.iman & XHCI_IMAN_INTR_PEND);
2034
2035                 if (!(value & XHCI_IMAN_INTR_ENA))
2036                         pci_xhci_deassert_interrupt(sc);
2037
2038                 break;
2039
2040         case 0x04:
2041                 rts->intrreg.imod = value;
2042                 break;
2043
2044         case 0x08:
2045                 rts->intrreg.erstsz = value & 0xFFFF;
2046                 break;
2047
2048         case 0x10:
2049                 /* ERSTBA low bits */
2050                 rts->intrreg.erstba = MASK_64_HI(sc->rtsregs.intrreg.erstba) |
2051                                       (value & ~0x3F);
2052                 break;
2053
2054         case 0x14:
2055                 /* ERSTBA high bits */
2056                 rts->intrreg.erstba = (value << 32) |
2057                     MASK_64_LO(sc->rtsregs.intrreg.erstba);
2058
2059                 rts->erstba_p = XHCI_GADDR(sc,
2060                                         sc->rtsregs.intrreg.erstba & ~0x3FUL);
2061
2062                 rts->erst_p = XHCI_GADDR(sc,
2063                               sc->rtsregs.erstba_p->qwEvrsTablePtr & ~0x3FUL);
2064
2065                 rts->er_enq_idx = 0;
2066                 rts->er_events_cnt = 0;
2067
2068                 DPRINTF(("pci_xhci: wr erstba erst (%p) ptr 0x%lx, sz %u",
2069                         rts->erstba_p,
2070                         rts->erstba_p->qwEvrsTablePtr,
2071                         rts->erstba_p->dwEvrsTableSize));
2072                 break;
2073
2074         case 0x18:
2075                 /* ERDP low bits */
2076                 rts->intrreg.erdp =
2077                     MASK_64_HI(sc->rtsregs.intrreg.erdp) |
2078                     (rts->intrreg.erdp & XHCI_ERDP_LO_BUSY) |
2079                     (value & ~0xF);
2080                 if (value & XHCI_ERDP_LO_BUSY) {
2081                         rts->intrreg.erdp &= ~XHCI_ERDP_LO_BUSY;
2082                         rts->intrreg.iman &= ~XHCI_IMAN_INTR_PEND;
2083                 }
2084
2085                 rts->er_deq_seg = XHCI_ERDP_LO_SINDEX(value);
2086
2087                 break;
2088
2089         case 0x1C:
2090                 /* ERDP high bits */
2091                 rts->intrreg.erdp = (value << 32) |
2092                     MASK_64_LO(sc->rtsregs.intrreg.erdp);
2093
2094                 if (rts->er_events_cnt > 0) {
2095                         uint64_t erdp;
2096                         uint32_t erdp_i;
2097
2098                         erdp = rts->intrreg.erdp & ~0xF;
2099                         erdp_i = (erdp - rts->erstba_p->qwEvrsTablePtr) /
2100                                    sizeof(struct xhci_trb);
2101
2102                         if (erdp_i <= rts->er_enq_idx)
2103                                 rts->er_events_cnt = rts->er_enq_idx - erdp_i;
2104                         else
2105                                 rts->er_events_cnt =
2106                                           rts->erstba_p->dwEvrsTableSize -
2107                                           (erdp_i - rts->er_enq_idx);
2108
2109                         DPRINTF(("pci_xhci: erdp 0x%lx, events cnt %u",
2110                                 erdp, rts->er_events_cnt));
2111                 }
2112
2113                 break;
2114
2115         default:
2116                 DPRINTF(("pci_xhci attempted write to RTS offset 0x%lx",
2117                         offset));
2118                 break;
2119         }
2120 }
2121
2122 static uint64_t
2123 pci_xhci_portregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2124 {
2125         int port;
2126         uint32_t *p;
2127
2128         if (sc->portregs == NULL)
2129                 return (0);
2130
2131         port = (offset - 0x3F0) / 0x10;
2132
2133         if (port > XHCI_MAX_DEVS) {
2134                 DPRINTF(("pci_xhci: portregs_read port %d >= XHCI_MAX_DEVS",
2135                     port));
2136
2137                 /* return default value for unused port */
2138                 return (XHCI_PS_SPEED_SET(3));
2139         }
2140
2141         offset = (offset - 0x3F0) % 0x10;
2142
2143         p = &sc->portregs[port].portsc;
2144         p += offset / sizeof(uint32_t);
2145
2146         DPRINTF(("pci_xhci: portregs read offset 0x%lx port %u -> 0x%x",
2147                 offset, port, *p));
2148
2149         return (*p);
2150 }
2151
2152 static void
2153 pci_xhci_hostop_write(struct pci_xhci_softc *sc, uint64_t offset,
2154     uint64_t value)
2155 {
2156         offset -= XHCI_CAPLEN;
2157
2158         if (offset < 0x400)
2159                 DPRINTF(("pci_xhci: hostop write offset 0x%lx: 0x%lx",
2160                          offset, value));
2161
2162         switch (offset) {
2163         case XHCI_USBCMD:
2164                 sc->opregs.usbcmd = pci_xhci_usbcmd_write(sc, value & 0x3F0F);
2165                 break;
2166
2167         case XHCI_USBSTS:
2168                 /* clear bits on write */
2169                 sc->opregs.usbsts &= ~(value &
2170                       (XHCI_STS_HSE|XHCI_STS_EINT|XHCI_STS_PCD|XHCI_STS_SSS|
2171                        XHCI_STS_RSS|XHCI_STS_SRE|XHCI_STS_CNR));
2172                 break;
2173
2174         case XHCI_PAGESIZE:
2175                 /* read only */
2176                 break;
2177
2178         case XHCI_DNCTRL:
2179                 sc->opregs.dnctrl = value & 0xFFFF;
2180                 break;
2181
2182         case XHCI_CRCR_LO:
2183                 if (sc->opregs.crcr & XHCI_CRCR_LO_CRR) {
2184                         sc->opregs.crcr &= ~(XHCI_CRCR_LO_CS|XHCI_CRCR_LO_CA);
2185                         sc->opregs.crcr |= value &
2186                                            (XHCI_CRCR_LO_CS|XHCI_CRCR_LO_CA);
2187                 } else {
2188                         sc->opregs.crcr = MASK_64_HI(sc->opregs.crcr) |
2189                                    (value & (0xFFFFFFC0 | XHCI_CRCR_LO_RCS));
2190                 }
2191                 break;
2192
2193         case XHCI_CRCR_HI:
2194                 if (!(sc->opregs.crcr & XHCI_CRCR_LO_CRR)) {
2195                         sc->opregs.crcr = MASK_64_LO(sc->opregs.crcr) |
2196                                           (value << 32);
2197
2198                         sc->opregs.cr_p = XHCI_GADDR(sc,
2199                                           sc->opregs.crcr & ~0xF);
2200                 }
2201
2202                 if (sc->opregs.crcr & XHCI_CRCR_LO_CS) {
2203                         /* Stop operation of Command Ring */
2204                 }
2205
2206                 if (sc->opregs.crcr & XHCI_CRCR_LO_CA) {
2207                         /* Abort command */
2208                 }
2209
2210                 break;
2211
2212         case XHCI_DCBAAP_LO:
2213                 sc->opregs.dcbaap = MASK_64_HI(sc->opregs.dcbaap) |
2214                                     (value & 0xFFFFFFC0);
2215                 break;
2216
2217         case XHCI_DCBAAP_HI:
2218                 sc->opregs.dcbaap =  MASK_64_LO(sc->opregs.dcbaap) |
2219                                      (value << 32);
2220                 sc->opregs.dcbaa_p = XHCI_GADDR(sc, sc->opregs.dcbaap & ~0x3FUL);
2221
2222                 DPRINTF(("pci_xhci: opregs dcbaap = 0x%lx (vaddr 0x%lx)",
2223                     sc->opregs.dcbaap, (uint64_t)sc->opregs.dcbaa_p));
2224                 break;
2225
2226         case XHCI_CONFIG:
2227                 sc->opregs.config = value & 0x03FF;
2228                 break;
2229
2230         default:
2231                 if (offset >= 0x400)
2232                         pci_xhci_portregs_write(sc, offset, value);
2233
2234                 break;
2235         }
2236 }
2237
2238
2239 static void
2240 pci_xhci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
2241                 int baridx, uint64_t offset, int size, uint64_t value)
2242 {
2243         struct pci_xhci_softc *sc;
2244
2245         sc = pi->pi_arg;
2246
2247         assert(baridx == 0);
2248
2249
2250         pthread_mutex_lock(&sc->mtx);
2251         if (offset < XHCI_CAPLEN)       /* read only registers */
2252                 WPRINTF(("pci_xhci: write RO-CAPs offset %ld", offset));
2253         else if (offset < sc->dboff)
2254                 pci_xhci_hostop_write(sc, offset, value);
2255         else if (offset < sc->rtsoff)
2256                 pci_xhci_dbregs_write(sc, offset, value);
2257         else if (offset < sc->regsend)
2258                 pci_xhci_rtsregs_write(sc, offset, value);
2259         else
2260                 WPRINTF(("pci_xhci: write invalid offset %ld", offset));
2261
2262         pthread_mutex_unlock(&sc->mtx);
2263 }
2264
2265 static uint64_t
2266 pci_xhci_hostcap_read(struct pci_xhci_softc *sc, uint64_t offset)
2267 {
2268         uint64_t        value;
2269
2270         switch (offset) {
2271         case XHCI_CAPLENGTH:    /* 0x00 */
2272                 value = sc->caplength;
2273                 break;
2274
2275         case XHCI_HCSPARAMS1:   /* 0x04 */
2276                 value = sc->hcsparams1;
2277                 break;
2278
2279         case XHCI_HCSPARAMS2:   /* 0x08 */
2280                 value = sc->hcsparams2;
2281                 break;
2282
2283         case XHCI_HCSPARAMS3:   /* 0x0C */
2284                 value = sc->hcsparams3;
2285                 break;
2286
2287         case XHCI_HCSPARAMS0:   /* 0x10 */
2288                 value = sc->hccparams1;
2289                 break;
2290
2291         case XHCI_DBOFF:        /* 0x14 */
2292                 value = sc->dboff;
2293                 break;
2294
2295         case XHCI_RTSOFF:       /* 0x18 */
2296                 value = sc->rtsoff;
2297                 break;
2298
2299         case XHCI_HCCPRAMS2:    /* 0x1C */
2300                 value = sc->hccparams2;
2301                 break;
2302
2303         default:
2304                 value = 0;
2305                 break;
2306         }
2307
2308         DPRINTF(("pci_xhci: hostcap read offset 0x%lx -> 0x%lx",
2309                 offset, value));
2310
2311         return (value);
2312 }
2313
2314 static uint64_t
2315 pci_xhci_hostop_read(struct pci_xhci_softc *sc, uint64_t offset)
2316 {
2317         uint64_t value;
2318
2319         offset = (offset - XHCI_CAPLEN);
2320
2321         switch (offset) {
2322         case XHCI_USBCMD:       /* 0x00 */
2323                 value = sc->opregs.usbcmd;
2324                 break;
2325
2326         case XHCI_USBSTS:       /* 0x04 */
2327                 value = sc->opregs.usbsts;
2328                 break;
2329
2330         case XHCI_PAGESIZE:     /* 0x08 */
2331                 value = sc->opregs.pgsz;
2332                 break;
2333
2334         case XHCI_DNCTRL:       /* 0x14 */
2335                 value = sc->opregs.dnctrl;
2336                 break;
2337
2338         case XHCI_CRCR_LO:      /* 0x18 */
2339                 value = sc->opregs.crcr & XHCI_CRCR_LO_CRR;
2340                 break;
2341
2342         case XHCI_CRCR_HI:      /* 0x1C */
2343                 value = 0;
2344                 break;
2345
2346         case XHCI_DCBAAP_LO:    /* 0x30 */
2347                 value = sc->opregs.dcbaap & 0xFFFFFFFF;
2348                 break;
2349
2350         case XHCI_DCBAAP_HI:    /* 0x34 */
2351                 value = (sc->opregs.dcbaap >> 32) & 0xFFFFFFFF;
2352                 break;
2353
2354         case XHCI_CONFIG:       /* 0x38 */
2355                 value = sc->opregs.config;
2356                 break;
2357
2358         default:
2359                 if (offset >= 0x400)
2360                         value = pci_xhci_portregs_read(sc, offset);
2361                 else
2362                         value = 0;
2363
2364                 break;
2365         }
2366
2367         if (offset < 0x400)
2368                 DPRINTF(("pci_xhci: hostop read offset 0x%lx -> 0x%lx",
2369                         offset, value));
2370
2371         return (value);
2372 }
2373
2374 static uint64_t
2375 pci_xhci_dbregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2376 {
2377
2378         /* read doorbell always returns 0 */
2379         return (0);
2380 }
2381
2382 static uint64_t
2383 pci_xhci_rtsregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2384 {
2385         uint32_t        value;
2386
2387         offset -= sc->rtsoff;
2388         value = 0;
2389
2390         if (offset == XHCI_MFINDEX) {
2391                 value = sc->rtsregs.mfindex;
2392         } else if (offset >= 0x20) {
2393                 int item;
2394                 uint32_t *p;
2395
2396                 offset -= 0x20;
2397                 item = offset % 32;
2398
2399                 assert(offset < sizeof(sc->rtsregs.intrreg));
2400
2401                 p = &sc->rtsregs.intrreg.iman;
2402                 p += item / sizeof(uint32_t);
2403                 value = *p;
2404         }
2405
2406         DPRINTF(("pci_xhci: rtsregs read offset 0x%lx -> 0x%x",
2407                 offset, value));
2408
2409         return (value);
2410 }
2411
2412 static uint64_t
2413 pci_xhci_xecp_read(struct pci_xhci_softc *sc, uint64_t offset)
2414 {
2415         uint32_t        value;
2416
2417         offset -= sc->regsend;
2418         value = 0;
2419
2420         switch (offset) {
2421         case 0:
2422                 /* rev major | rev minor | next-cap | cap-id */
2423                 value = (0x02 << 24) | (4 << 8) | XHCI_ID_PROTOCOLS;
2424                 break;
2425         case 4:
2426                 /* name string = "USB" */
2427                 value = 0x20425355;
2428                 break;
2429         case 8:
2430                 /* psic | proto-defined | compat # | compat offset */
2431                 value = ((XHCI_MAX_DEVS/2) << 8) | sc->usb2_port_start;
2432                 break;
2433         case 12:
2434                 break;
2435         case 16:
2436                 /* rev major | rev minor | next-cap | cap-id */
2437                 value = (0x03 << 24) | XHCI_ID_PROTOCOLS;
2438                 break;
2439         case 20:
2440                 /* name string = "USB" */
2441                 value = 0x20425355;
2442                 break;
2443         case 24:
2444                 /* psic | proto-defined | compat # | compat offset */
2445                 value = ((XHCI_MAX_DEVS/2) << 8) | sc->usb3_port_start;
2446                 break;
2447         case 28:
2448                 break;
2449         default:
2450                 DPRINTF(("pci_xhci: xecp invalid offset 0x%lx", offset));
2451                 break;
2452         }
2453
2454         DPRINTF(("pci_xhci: xecp read offset 0x%lx -> 0x%x",
2455                 offset, value));
2456
2457         return (value);
2458 }
2459
2460
2461 static uint64_t
2462 pci_xhci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2463     uint64_t offset, int size)
2464 {
2465         struct pci_xhci_softc *sc;
2466         uint32_t        value;
2467
2468         sc = pi->pi_arg;
2469
2470         assert(baridx == 0);
2471
2472         pthread_mutex_lock(&sc->mtx);
2473         if (offset < XHCI_CAPLEN)
2474                 value = pci_xhci_hostcap_read(sc, offset);
2475         else if (offset < sc->dboff)
2476                 value = pci_xhci_hostop_read(sc, offset);
2477         else if (offset < sc->rtsoff)
2478                 value = pci_xhci_dbregs_read(sc, offset);
2479         else if (offset < sc->regsend)
2480                 value = pci_xhci_rtsregs_read(sc, offset);
2481         else if (offset < (sc->regsend + 4*32))
2482                 value = pci_xhci_xecp_read(sc, offset);
2483         else {
2484                 value = 0;
2485                 WPRINTF(("pci_xhci: read invalid offset %ld", offset));
2486         }
2487
2488         pthread_mutex_unlock(&sc->mtx);
2489
2490         switch (size) {
2491         case 1:
2492                 value &= 0xFF;
2493                 break;
2494         case 2:
2495                 value &= 0xFFFF;
2496                 break;
2497         case 4:
2498                 value &= 0xFFFFFFFF;
2499                 break;
2500         }
2501
2502         return (value);
2503 }
2504
2505 static void
2506 pci_xhci_reset_port(struct pci_xhci_softc *sc, int portn, int warm)
2507 {
2508         struct pci_xhci_portregs *port;
2509         struct pci_xhci_dev_emu *dev;
2510         struct xhci_trb         evtrb;
2511         int     error;
2512
2513         assert(portn <= XHCI_MAX_DEVS);
2514
2515         DPRINTF(("xhci reset port %d", portn));
2516
2517         port = XHCI_PORTREG_PTR(sc, portn);
2518         dev = XHCI_DEVINST_PTR(sc, portn);
2519         if (dev) {
2520                 port->portsc &= ~(XHCI_PS_PLS_MASK | XHCI_PS_PR | XHCI_PS_PRC);
2521                 port->portsc |= XHCI_PS_PED |
2522                     XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2523
2524                 if (warm && dev->dev_ue->ue_usbver == 3) {
2525                         port->portsc |= XHCI_PS_WRC;
2526                 }
2527
2528                 if ((port->portsc & XHCI_PS_PRC) == 0) {
2529                         port->portsc |= XHCI_PS_PRC;
2530
2531                         pci_xhci_set_evtrb(&evtrb, portn,
2532                              XHCI_TRB_ERROR_SUCCESS,
2533                              XHCI_TRB_EVENT_PORT_STS_CHANGE);
2534                         error = pci_xhci_insert_event(sc, &evtrb, 1);
2535                         if (error != XHCI_TRB_ERROR_SUCCESS)
2536                                 DPRINTF(("xhci reset port insert event "
2537                                          "failed"));
2538                 }
2539         }
2540 }
2541
2542 static void
2543 pci_xhci_init_port(struct pci_xhci_softc *sc, int portn)
2544 {
2545         struct pci_xhci_portregs *port;
2546         struct pci_xhci_dev_emu *dev;
2547
2548         port = XHCI_PORTREG_PTR(sc, portn);
2549         dev = XHCI_DEVINST_PTR(sc, portn);
2550         if (dev) {
2551                 port->portsc = XHCI_PS_CCS |            /* connected */
2552                                XHCI_PS_PP;              /* port power */
2553                 
2554                 if (dev->dev_ue->ue_usbver == 2) {
2555                         port->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_POLL) |
2556                                XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2557                 } else {
2558                         port->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_U0) |
2559                                XHCI_PS_PED |            /* enabled */
2560                                XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2561                 }
2562                 
2563                 DPRINTF(("Init port %d 0x%x", portn, port->portsc));
2564         } else {
2565                 port->portsc = XHCI_PS_PLS_SET(UPS_PORT_LS_RX_DET) | XHCI_PS_PP;
2566                 DPRINTF(("Init empty port %d 0x%x", portn, port->portsc));
2567         }
2568 }
2569
2570 static int
2571 pci_xhci_dev_intr(struct usb_hci *hci, int epctx)
2572 {
2573         struct pci_xhci_dev_emu *dev;
2574         struct xhci_dev_ctx     *dev_ctx;
2575         struct xhci_trb         evtrb;
2576         struct pci_xhci_softc   *sc;
2577         struct pci_xhci_portregs *p;
2578         struct xhci_endp_ctx    *ep_ctx;
2579         int     error = 0;
2580         int     dir_in;
2581         int     epid;
2582
2583         dir_in = epctx & 0x80;
2584         epid = epctx & ~0x80;
2585
2586         /* HW endpoint contexts are 0-15; convert to epid based on dir */
2587         epid = (epid * 2) + (dir_in ? 1 : 0);
2588
2589         assert(epid >= 1 && epid <= 31);
2590
2591         dev = hci->hci_sc;
2592         sc = dev->xsc;
2593
2594         /* check if device is ready; OS has to initialise it */
2595         if (sc->rtsregs.erstba_p == NULL ||
2596             (sc->opregs.usbcmd & XHCI_CMD_RS) == 0 ||
2597             dev->dev_ctx == NULL)
2598                 return (0);
2599
2600         p = XHCI_PORTREG_PTR(sc, hci->hci_port);
2601
2602         /* raise event if link U3 (suspended) state */
2603         if (XHCI_PS_PLS_GET(p->portsc) == 3) {
2604                 p->portsc &= ~XHCI_PS_PLS_MASK;
2605                 p->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_RESUME);
2606                 if ((p->portsc & XHCI_PS_PLC) != 0)
2607                         return (0);
2608
2609                 p->portsc |= XHCI_PS_PLC;
2610
2611                 pci_xhci_set_evtrb(&evtrb, hci->hci_port,
2612                       XHCI_TRB_ERROR_SUCCESS, XHCI_TRB_EVENT_PORT_STS_CHANGE);
2613                 error = pci_xhci_insert_event(sc, &evtrb, 0);
2614                 if (error != XHCI_TRB_ERROR_SUCCESS)
2615                         goto done;
2616         }
2617
2618         dev_ctx = dev->dev_ctx;
2619         ep_ctx = &dev_ctx->ctx_ep[epid];
2620         if ((ep_ctx->dwEpCtx0 & 0x7) == XHCI_ST_EPCTX_DISABLED) {
2621                 DPRINTF(("xhci device interrupt on disabled endpoint %d",
2622                          epid));
2623                 return (0);
2624         }
2625
2626         DPRINTF(("xhci device interrupt on endpoint %d", epid));
2627
2628         pci_xhci_device_doorbell(sc, hci->hci_port, epid, 0);
2629
2630 done:
2631         return (error);
2632 }
2633
2634 static int
2635 pci_xhci_dev_event(struct usb_hci *hci, enum hci_usbev evid, void *param)
2636 {
2637
2638         DPRINTF(("xhci device event port %d", hci->hci_port));
2639         return (0);
2640 }
2641
2642
2643
2644 static void
2645 pci_xhci_device_usage(char *opt)
2646 {
2647
2648         EPRINTLN("Invalid USB emulation \"%s\"", opt);
2649 }
2650
2651 static int
2652 pci_xhci_parse_opts(struct pci_xhci_softc *sc, char *opts)
2653 {
2654         struct pci_xhci_dev_emu **devices;
2655         struct pci_xhci_dev_emu *dev;
2656         struct usb_devemu       *ue;
2657         void    *devsc;
2658         char    *uopt, *xopts, *config;
2659         int     usb3_port, usb2_port, i;
2660
2661         uopt = NULL;
2662         usb3_port = sc->usb3_port_start - 1;
2663         usb2_port = sc->usb2_port_start - 1;
2664         devices = NULL;
2665
2666         if (opts == NULL)
2667                 goto portsfinal;
2668
2669         devices = calloc(XHCI_MAX_DEVS, sizeof(struct pci_xhci_dev_emu *));
2670
2671         sc->slots = calloc(XHCI_MAX_SLOTS, sizeof(struct pci_xhci_dev_emu *));
2672         sc->devices = devices;
2673         sc->ndevices = 0;
2674
2675         uopt = strdup(opts);
2676         for (xopts = strtok(uopt, ",");
2677              xopts != NULL;
2678              xopts = strtok(NULL, ",")) {
2679                 if (usb2_port == ((sc->usb2_port_start-1) + XHCI_MAX_DEVS/2) ||
2680                     usb3_port == ((sc->usb3_port_start-1) + XHCI_MAX_DEVS/2)) {
2681                         WPRINTF(("pci_xhci max number of USB 2 or 3 "
2682                              "devices reached, max %d", XHCI_MAX_DEVS/2));
2683                         usb2_port = usb3_port = -1;
2684                         goto done;
2685                 }
2686
2687                 /* device[=<config>] */
2688                 if ((config = strchr(xopts, '=')) == NULL)
2689                         config = "";            /* no config */
2690                 else
2691                         *config++ = '\0';
2692
2693                 ue = usb_emu_finddev(xopts);
2694                 if (ue == NULL) {
2695                         pci_xhci_device_usage(xopts);
2696                         DPRINTF(("pci_xhci device not found %s", xopts));
2697                         usb2_port = usb3_port = -1;
2698                         goto done;
2699                 }
2700
2701                 DPRINTF(("pci_xhci adding device %s, opts \"%s\"",
2702                         xopts, config));
2703
2704                 dev = calloc(1, sizeof(struct pci_xhci_dev_emu));
2705                 dev->xsc = sc;
2706                 dev->hci.hci_sc = dev;
2707                 dev->hci.hci_intr = pci_xhci_dev_intr;
2708                 dev->hci.hci_event = pci_xhci_dev_event;
2709
2710                 if (ue->ue_usbver == 2) {
2711                         dev->hci.hci_port = usb2_port + 1;
2712                         devices[usb2_port] = dev;
2713                         usb2_port++;
2714                 } else {
2715                         dev->hci.hci_port = usb3_port + 1;
2716                         devices[usb3_port] = dev;
2717                         usb3_port++;
2718                 }
2719
2720                 dev->hci.hci_address = 0;
2721                 devsc = ue->ue_init(&dev->hci, config);
2722                 if (devsc == NULL) {
2723                         pci_xhci_device_usage(xopts);
2724                         usb2_port = usb3_port = -1;
2725                         goto done;
2726                 }
2727
2728                 dev->dev_ue = ue;
2729                 dev->dev_sc = devsc;
2730
2731                 /* assign slot number to device */
2732                 sc->slots[sc->ndevices] = dev;
2733
2734                 sc->ndevices++;
2735         }
2736
2737 portsfinal:
2738         sc->portregs = calloc(XHCI_MAX_DEVS, sizeof(struct pci_xhci_portregs));
2739
2740         if (sc->ndevices > 0) {
2741                 /* port and slot numbering start from 1 */
2742                 sc->devices--;
2743                 sc->portregs--;
2744                 sc->slots--;
2745
2746                 for (i = 1; i <= XHCI_MAX_DEVS; i++) {
2747                         pci_xhci_init_port(sc, i);
2748                 }
2749         } else {
2750                 WPRINTF(("pci_xhci no USB devices configured"));
2751                 sc->ndevices = 1;
2752         }
2753
2754 done:
2755         if (devices != NULL) {
2756                 if (usb2_port <= 0 && usb3_port <= 0) {
2757                         sc->devices = NULL;
2758                         for (i = 0; devices[i] != NULL; i++)
2759                                 free(devices[i]);
2760                         sc->ndevices = -1;
2761
2762                         free(devices);
2763                 }
2764         }
2765         free(uopt);
2766         return (sc->ndevices);
2767 }
2768
2769 static int
2770 pci_xhci_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2771 {
2772         struct pci_xhci_softc *sc;
2773         int     error;
2774
2775         if (xhci_in_use) {
2776                 WPRINTF(("pci_xhci controller already defined"));
2777                 return (-1);
2778         }
2779         xhci_in_use = 1;
2780
2781         sc = calloc(1, sizeof(struct pci_xhci_softc));
2782         pi->pi_arg = sc;
2783         sc->xsc_pi = pi;
2784
2785         sc->usb2_port_start = (XHCI_MAX_DEVS/2) + 1;
2786         sc->usb3_port_start = 1;
2787
2788         /* discover devices */
2789         error = pci_xhci_parse_opts(sc, opts);
2790         if (error < 0)
2791                 goto done;
2792         else
2793                 error = 0;
2794
2795         sc->caplength = XHCI_SET_CAPLEN(XHCI_CAPLEN) |
2796                         XHCI_SET_HCIVERSION(0x0100);
2797         sc->hcsparams1 = XHCI_SET_HCSP1_MAXPORTS(XHCI_MAX_DEVS) |
2798                          XHCI_SET_HCSP1_MAXINTR(1) |    /* interrupters */
2799                          XHCI_SET_HCSP1_MAXSLOTS(XHCI_MAX_SLOTS);
2800         sc->hcsparams2 = XHCI_SET_HCSP2_ERSTMAX(XHCI_ERST_MAX) |
2801                          XHCI_SET_HCSP2_IST(0x04);
2802         sc->hcsparams3 = 0;                             /* no latency */
2803         sc->hccparams1 = XHCI_SET_HCCP1_NSS(1) |        /* no 2nd-streams */
2804                          XHCI_SET_HCCP1_SPC(1) |        /* short packet */
2805                          XHCI_SET_HCCP1_MAXPSA(XHCI_STREAMS_MAX);
2806         sc->hccparams2 = XHCI_SET_HCCP2_LEC(1) |
2807                          XHCI_SET_HCCP2_U3C(1);
2808         sc->dboff = XHCI_SET_DOORBELL(XHCI_CAPLEN + XHCI_PORTREGS_START +
2809                     XHCI_MAX_DEVS * sizeof(struct pci_xhci_portregs));
2810
2811         /* dboff must be 32-bit aligned */
2812         if (sc->dboff & 0x3)
2813                 sc->dboff = (sc->dboff + 0x3) & ~0x3;
2814
2815         /* rtsoff must be 32-bytes aligned */
2816         sc->rtsoff = XHCI_SET_RTSOFFSET(sc->dboff + (XHCI_MAX_SLOTS+1) * 32);
2817         if (sc->rtsoff & 0x1F)
2818                 sc->rtsoff = (sc->rtsoff + 0x1F) & ~0x1F;
2819
2820         DPRINTF(("pci_xhci dboff: 0x%x, rtsoff: 0x%x", sc->dboff,
2821                 sc->rtsoff));
2822
2823         sc->opregs.usbsts = XHCI_STS_HCH;
2824         sc->opregs.pgsz = XHCI_PAGESIZE_4K;
2825
2826         pci_xhci_reset(sc);
2827
2828         sc->regsend = sc->rtsoff + 0x20 + 32;           /* only 1 intrpter */
2829
2830         /*
2831          * Set extended capabilities pointer to be after regsend;
2832          * value of xecp field is 32-bit offset.
2833          */
2834         sc->hccparams1 |= XHCI_SET_HCCP1_XECP(sc->regsend/4);
2835
2836         pci_set_cfgdata16(pi, PCIR_DEVICE, 0x1E31);
2837         pci_set_cfgdata16(pi, PCIR_VENDOR, 0x8086);
2838         pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_SERIALBUS);
2839         pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_SERIALBUS_USB);
2840         pci_set_cfgdata8(pi, PCIR_PROGIF,PCIP_SERIALBUS_USB_XHCI);
2841         pci_set_cfgdata8(pi, PCI_USBREV, PCI_USB_REV_3_0);
2842
2843         pci_emul_add_msicap(pi, 1);
2844
2845         /* regsend + xecp registers */
2846         pci_emul_alloc_bar(pi, 0, PCIBAR_MEM32, sc->regsend + 4*32);
2847         DPRINTF(("pci_xhci pci_emu_alloc: %d", sc->regsend + 4*32));
2848
2849
2850         pci_lintr_request(pi);
2851
2852         pthread_mutex_init(&sc->mtx, NULL);
2853
2854 done:
2855         if (error) {
2856                 free(sc);
2857         }
2858
2859         return (error);
2860 }
2861
2862
2863
2864 struct pci_devemu pci_de_xhci = {
2865         .pe_emu =       "xhci",
2866         .pe_init =      pci_xhci_init,
2867         .pe_barwrite =  pci_xhci_write,
2868         .pe_barread =   pci_xhci_read
2869 };
2870 PCI_EMUL_SET(pci_de_xhci);