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