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