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