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