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