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