xref: /freebsd/usr.sbin/bhyve/pci_xhci.c (revision 389e4940069316fe667ffa263fa7d6390d0a960f)
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 	dev = XHCI_SLOTDEV_PTR(sc, slot);
1904 	devep = &dev->eps[epid];
1905 	dev_ctx = pci_xhci_get_dev_ctx(sc, slot);
1906 	if (!dev_ctx) {
1907 		return;
1908 	}
1909 	ep_ctx = &dev_ctx->ctx_ep[epid];
1910 
1911 	sctx_tr = NULL;
1912 
1913 	DPRINTF(("pci_xhci: device doorbell ep[%u] %08x %08x %016lx %08x\r\n",
1914 	        epid, ep_ctx->dwEpCtx0, ep_ctx->dwEpCtx1, ep_ctx->qwEpCtx2,
1915 	        ep_ctx->dwEpCtx4));
1916 
1917 	if (ep_ctx->qwEpCtx2 == 0)
1918 		return;
1919 
1920 	/* handle pending transfers */
1921 	if (devep->ep_xfer->ndata > 0) {
1922 		pci_xhci_try_usb_xfer(sc, dev, devep, ep_ctx, slot, epid);
1923 		return;
1924 	}
1925 
1926 	/* get next trb work item */
1927 	if (XHCI_EPCTX_0_MAXP_STREAMS_GET(ep_ctx->dwEpCtx0) != 0) {
1928 		sctx_tr = &devep->ep_sctx_trbs[streamid];
1929 		ringaddr = sctx_tr->ringaddr;
1930 		ccs = sctx_tr->ccs;
1931 		trb = XHCI_GADDR(sc, sctx_tr->ringaddr & ~0xFUL);
1932 		DPRINTF(("doorbell, stream %u, ccs %lx, trb ccs %x\r\n",
1933 		        streamid, ep_ctx->qwEpCtx2 & XHCI_TRB_3_CYCLE_BIT,
1934 		        trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT));
1935 	} else {
1936 		ringaddr = devep->ep_ringaddr;
1937 		ccs = devep->ep_ccs;
1938 		trb = devep->ep_tr;
1939 		DPRINTF(("doorbell, ccs %lx, trb ccs %x\r\n",
1940 		        ep_ctx->qwEpCtx2 & XHCI_TRB_3_CYCLE_BIT,
1941 		        trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT));
1942 	}
1943 
1944 	if (XHCI_TRB_3_TYPE_GET(trb->dwTrb3) == 0) {
1945 		DPRINTF(("pci_xhci: ring %lx trb[%lx] EP %u is RESERVED?\r\n",
1946 		        ep_ctx->qwEpCtx2, devep->ep_ringaddr, epid));
1947 		return;
1948 	}
1949 
1950 	pci_xhci_handle_transfer(sc, dev, devep, ep_ctx, trb, slot, epid,
1951 	                         ringaddr, ccs, streamid);
1952 }
1953 
1954 static void
1955 pci_xhci_dbregs_write(struct pci_xhci_softc *sc, uint64_t offset,
1956     uint64_t value)
1957 {
1958 
1959 	offset = (offset - sc->dboff) / sizeof(uint32_t);
1960 
1961 	DPRINTF(("pci_xhci: doorbell write offset 0x%lx: 0x%lx\r\n",
1962 	        offset, value));
1963 
1964 	if (XHCI_HALTED(sc)) {
1965 		DPRINTF(("pci_xhci: controller halted\r\n"));
1966 		return;
1967 	}
1968 
1969 	if (offset == 0)
1970 		pci_xhci_complete_commands(sc);
1971 	else if (sc->portregs != NULL)
1972 		pci_xhci_device_doorbell(sc, offset,
1973 		   XHCI_DB_TARGET_GET(value), XHCI_DB_SID_GET(value));
1974 }
1975 
1976 static void
1977 pci_xhci_rtsregs_write(struct pci_xhci_softc *sc, uint64_t offset,
1978     uint64_t value)
1979 {
1980 	struct pci_xhci_rtsregs *rts;
1981 
1982 	offset -= sc->rtsoff;
1983 
1984 	if (offset == 0) {
1985 		DPRINTF(("pci_xhci attempted write to MFINDEX\r\n"));
1986 		return;
1987 	}
1988 
1989 	DPRINTF(("pci_xhci: runtime regs write offset 0x%lx: 0x%lx\r\n",
1990 	        offset, value));
1991 
1992 	offset -= 0x20;		/* start of intrreg */
1993 
1994 	rts = &sc->rtsregs;
1995 
1996 	switch (offset) {
1997 	case 0x00:
1998 		if (value & XHCI_IMAN_INTR_PEND)
1999 			rts->intrreg.iman &= ~XHCI_IMAN_INTR_PEND;
2000 		rts->intrreg.iman = (value & XHCI_IMAN_INTR_ENA) |
2001 		                    (rts->intrreg.iman & XHCI_IMAN_INTR_PEND);
2002 
2003 		if (!(value & XHCI_IMAN_INTR_ENA))
2004 			pci_xhci_deassert_interrupt(sc);
2005 
2006 		break;
2007 
2008 	case 0x04:
2009 		rts->intrreg.imod = value;
2010 		break;
2011 
2012 	case 0x08:
2013 		rts->intrreg.erstsz = value & 0xFFFF;
2014 		break;
2015 
2016 	case 0x10:
2017 		/* ERSTBA low bits */
2018 		rts->intrreg.erstba = MASK_64_HI(sc->rtsregs.intrreg.erstba) |
2019 		                      (value & ~0x3F);
2020 		break;
2021 
2022 	case 0x14:
2023 		/* ERSTBA high bits */
2024 		rts->intrreg.erstba = (value << 32) |
2025 		    MASK_64_LO(sc->rtsregs.intrreg.erstba);
2026 
2027 		rts->erstba_p = XHCI_GADDR(sc,
2028 		                        sc->rtsregs.intrreg.erstba & ~0x3FUL);
2029 
2030 		rts->erst_p = XHCI_GADDR(sc,
2031 		              sc->rtsregs.erstba_p->qwEvrsTablePtr & ~0x3FUL);
2032 
2033 		rts->er_enq_idx = 0;
2034 		rts->er_events_cnt = 0;
2035 
2036 		DPRINTF(("pci_xhci: wr erstba erst (%p) ptr 0x%lx, sz %u\r\n",
2037 		        rts->erstba_p,
2038 		        rts->erstba_p->qwEvrsTablePtr,
2039 		        rts->erstba_p->dwEvrsTableSize));
2040 		break;
2041 
2042 	case 0x18:
2043 		/* ERDP low bits */
2044 		rts->intrreg.erdp =
2045 		    MASK_64_HI(sc->rtsregs.intrreg.erdp) |
2046 		    (rts->intrreg.erdp & XHCI_ERDP_LO_BUSY) |
2047 		    (value & ~0xF);
2048 		if (value & XHCI_ERDP_LO_BUSY) {
2049 			rts->intrreg.erdp &= ~XHCI_ERDP_LO_BUSY;
2050 			rts->intrreg.iman &= ~XHCI_IMAN_INTR_PEND;
2051 		}
2052 
2053 		rts->er_deq_seg = XHCI_ERDP_LO_SINDEX(value);
2054 
2055 		break;
2056 
2057 	case 0x1C:
2058 		/* ERDP high bits */
2059 		rts->intrreg.erdp = (value << 32) |
2060 		    MASK_64_LO(sc->rtsregs.intrreg.erdp);
2061 
2062 		if (rts->er_events_cnt > 0) {
2063 			uint64_t erdp;
2064 			uint32_t erdp_i;
2065 
2066 			erdp = rts->intrreg.erdp & ~0xF;
2067 			erdp_i = (erdp - rts->erstba_p->qwEvrsTablePtr) /
2068 			           sizeof(struct xhci_trb);
2069 
2070 			if (erdp_i <= rts->er_enq_idx)
2071 				rts->er_events_cnt = rts->er_enq_idx - erdp_i;
2072 			else
2073 				rts->er_events_cnt =
2074 				          rts->erstba_p->dwEvrsTableSize -
2075 				          (erdp_i - rts->er_enq_idx);
2076 
2077 			DPRINTF(("pci_xhci: erdp 0x%lx, events cnt %u\r\n",
2078 			        erdp, rts->er_events_cnt));
2079 		}
2080 
2081 		break;
2082 
2083 	default:
2084 		DPRINTF(("pci_xhci attempted write to RTS offset 0x%lx\r\n",
2085 		        offset));
2086 		break;
2087 	}
2088 }
2089 
2090 static uint64_t
2091 pci_xhci_portregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2092 {
2093 	int port;
2094 	uint32_t *p;
2095 
2096 	if (sc->portregs == NULL)
2097 		return (0);
2098 
2099 	port = (offset - 0x3F0) / 0x10;
2100 
2101 	if (port > XHCI_MAX_DEVS) {
2102 		DPRINTF(("pci_xhci: portregs_read port %d >= XHCI_MAX_DEVS\r\n",
2103 		    port));
2104 
2105 		/* return default value for unused port */
2106 		return (XHCI_PS_SPEED_SET(3));
2107 	}
2108 
2109 	offset = (offset - 0x3F0) % 0x10;
2110 
2111 	p = &sc->portregs[port].portsc;
2112 	p += offset / sizeof(uint32_t);
2113 
2114 	DPRINTF(("pci_xhci: portregs read offset 0x%lx port %u -> 0x%x\r\n",
2115 	        offset, port, *p));
2116 
2117 	return (*p);
2118 }
2119 
2120 static void
2121 pci_xhci_hostop_write(struct pci_xhci_softc *sc, uint64_t offset,
2122     uint64_t value)
2123 {
2124 	offset -= XHCI_CAPLEN;
2125 
2126 	if (offset < 0x400)
2127 		DPRINTF(("pci_xhci: hostop write offset 0x%lx: 0x%lx\r\n",
2128 		         offset, value));
2129 
2130 	switch (offset) {
2131 	case XHCI_USBCMD:
2132 		sc->opregs.usbcmd = pci_xhci_usbcmd_write(sc, value & 0x3F0F);
2133 		break;
2134 
2135 	case XHCI_USBSTS:
2136 		/* clear bits on write */
2137 		sc->opregs.usbsts &= ~(value &
2138 		      (XHCI_STS_HSE|XHCI_STS_EINT|XHCI_STS_PCD|XHCI_STS_SSS|
2139 		       XHCI_STS_RSS|XHCI_STS_SRE|XHCI_STS_CNR));
2140 		break;
2141 
2142 	case XHCI_PAGESIZE:
2143 		/* read only */
2144 		break;
2145 
2146 	case XHCI_DNCTRL:
2147 		sc->opregs.dnctrl = value & 0xFFFF;
2148 		break;
2149 
2150 	case XHCI_CRCR_LO:
2151 		if (sc->opregs.crcr & XHCI_CRCR_LO_CRR) {
2152 			sc->opregs.crcr &= ~(XHCI_CRCR_LO_CS|XHCI_CRCR_LO_CA);
2153 			sc->opregs.crcr |= value &
2154 			                   (XHCI_CRCR_LO_CS|XHCI_CRCR_LO_CA);
2155 		} else {
2156 			sc->opregs.crcr = MASK_64_HI(sc->opregs.crcr) |
2157 			           (value & (0xFFFFFFC0 | XHCI_CRCR_LO_RCS));
2158 		}
2159 		break;
2160 
2161 	case XHCI_CRCR_HI:
2162 		if (!(sc->opregs.crcr & XHCI_CRCR_LO_CRR)) {
2163 			sc->opregs.crcr = MASK_64_LO(sc->opregs.crcr) |
2164 			                  (value << 32);
2165 
2166 			sc->opregs.cr_p = XHCI_GADDR(sc,
2167 			                  sc->opregs.crcr & ~0xF);
2168 		}
2169 
2170 		if (sc->opregs.crcr & XHCI_CRCR_LO_CS) {
2171 			/* Stop operation of Command Ring */
2172 		}
2173 
2174 		if (sc->opregs.crcr & XHCI_CRCR_LO_CA) {
2175 			/* Abort command */
2176 		}
2177 
2178 		break;
2179 
2180 	case XHCI_DCBAAP_LO:
2181 		sc->opregs.dcbaap = MASK_64_HI(sc->opregs.dcbaap) |
2182 		                    (value & 0xFFFFFFC0);
2183 		break;
2184 
2185 	case XHCI_DCBAAP_HI:
2186 		sc->opregs.dcbaap =  MASK_64_LO(sc->opregs.dcbaap) |
2187 		                     (value << 32);
2188 		sc->opregs.dcbaa_p = XHCI_GADDR(sc, sc->opregs.dcbaap & ~0x3FUL);
2189 
2190 		DPRINTF(("pci_xhci: opregs dcbaap = 0x%lx (vaddr 0x%lx)\r\n",
2191 		    sc->opregs.dcbaap, (uint64_t)sc->opregs.dcbaa_p));
2192 		break;
2193 
2194 	case XHCI_CONFIG:
2195 		sc->opregs.config = value & 0x03FF;
2196 		break;
2197 
2198 	default:
2199 		if (offset >= 0x400)
2200 			pci_xhci_portregs_write(sc, offset, value);
2201 
2202 		break;
2203 	}
2204 }
2205 
2206 
2207 static void
2208 pci_xhci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
2209                 int baridx, uint64_t offset, int size, uint64_t value)
2210 {
2211 	struct pci_xhci_softc *sc;
2212 
2213 	sc = pi->pi_arg;
2214 
2215 	assert(baridx == 0);
2216 
2217 
2218 	pthread_mutex_lock(&sc->mtx);
2219 	if (offset < XHCI_CAPLEN)	/* read only registers */
2220 		WPRINTF(("pci_xhci: write RO-CAPs offset %ld\r\n", offset));
2221 	else if (offset < sc->dboff)
2222 		pci_xhci_hostop_write(sc, offset, value);
2223 	else if (offset < sc->rtsoff)
2224 		pci_xhci_dbregs_write(sc, offset, value);
2225 	else if (offset < sc->regsend)
2226 		pci_xhci_rtsregs_write(sc, offset, value);
2227 	else
2228 		WPRINTF(("pci_xhci: write invalid offset %ld\r\n", offset));
2229 
2230 	pthread_mutex_unlock(&sc->mtx);
2231 }
2232 
2233 static uint64_t
2234 pci_xhci_hostcap_read(struct pci_xhci_softc *sc, uint64_t offset)
2235 {
2236 	uint64_t	value;
2237 
2238 	switch (offset) {
2239 	case XHCI_CAPLENGTH:	/* 0x00 */
2240 		value = sc->caplength;
2241 		break;
2242 
2243 	case XHCI_HCSPARAMS1:	/* 0x04 */
2244 		value = sc->hcsparams1;
2245 		break;
2246 
2247 	case XHCI_HCSPARAMS2:	/* 0x08 */
2248 		value = sc->hcsparams2;
2249 		break;
2250 
2251 	case XHCI_HCSPARAMS3:	/* 0x0C */
2252 		value = sc->hcsparams3;
2253 		break;
2254 
2255 	case XHCI_HCSPARAMS0:	/* 0x10 */
2256 		value = sc->hccparams1;
2257 		break;
2258 
2259 	case XHCI_DBOFF:	/* 0x14 */
2260 		value = sc->dboff;
2261 		break;
2262 
2263 	case XHCI_RTSOFF:	/* 0x18 */
2264 		value = sc->rtsoff;
2265 		break;
2266 
2267 	case XHCI_HCCPRAMS2:	/* 0x1C */
2268 		value = sc->hccparams2;
2269 		break;
2270 
2271 	default:
2272 		value = 0;
2273 		break;
2274 	}
2275 
2276 	DPRINTF(("pci_xhci: hostcap read offset 0x%lx -> 0x%lx\r\n",
2277 	        offset, value));
2278 
2279 	return (value);
2280 }
2281 
2282 static uint64_t
2283 pci_xhci_hostop_read(struct pci_xhci_softc *sc, uint64_t offset)
2284 {
2285 	uint64_t value;
2286 
2287 	offset = (offset - XHCI_CAPLEN);
2288 
2289 	switch (offset) {
2290 	case XHCI_USBCMD:	/* 0x00 */
2291 		value = sc->opregs.usbcmd;
2292 		break;
2293 
2294 	case XHCI_USBSTS:	/* 0x04 */
2295 		value = sc->opregs.usbsts;
2296 		break;
2297 
2298 	case XHCI_PAGESIZE:	/* 0x08 */
2299 		value = sc->opregs.pgsz;
2300 		break;
2301 
2302 	case XHCI_DNCTRL:	/* 0x14 */
2303 		value = sc->opregs.dnctrl;
2304 		break;
2305 
2306 	case XHCI_CRCR_LO:	/* 0x18 */
2307 		value = sc->opregs.crcr & XHCI_CRCR_LO_CRR;
2308 		break;
2309 
2310 	case XHCI_CRCR_HI:	/* 0x1C */
2311 		value = 0;
2312 		break;
2313 
2314 	case XHCI_DCBAAP_LO:	/* 0x30 */
2315 		value = sc->opregs.dcbaap & 0xFFFFFFFF;
2316 		break;
2317 
2318 	case XHCI_DCBAAP_HI:	/* 0x34 */
2319 		value = (sc->opregs.dcbaap >> 32) & 0xFFFFFFFF;
2320 		break;
2321 
2322 	case XHCI_CONFIG:	/* 0x38 */
2323 		value = sc->opregs.config;
2324 		break;
2325 
2326 	default:
2327 		if (offset >= 0x400)
2328 			value = pci_xhci_portregs_read(sc, offset);
2329 		else
2330 			value = 0;
2331 
2332 		break;
2333 	}
2334 
2335 	if (offset < 0x400)
2336 		DPRINTF(("pci_xhci: hostop read offset 0x%lx -> 0x%lx\r\n",
2337 		        offset, value));
2338 
2339 	return (value);
2340 }
2341 
2342 static uint64_t
2343 pci_xhci_dbregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2344 {
2345 
2346 	/* read doorbell always returns 0 */
2347 	return (0);
2348 }
2349 
2350 static uint64_t
2351 pci_xhci_rtsregs_read(struct pci_xhci_softc *sc, uint64_t offset)
2352 {
2353 	uint32_t	value;
2354 
2355 	offset -= sc->rtsoff;
2356 	value = 0;
2357 
2358 	if (offset == XHCI_MFINDEX) {
2359 		value = sc->rtsregs.mfindex;
2360 	} else if (offset >= 0x20) {
2361 		int item;
2362 		uint32_t *p;
2363 
2364 		offset -= 0x20;
2365 		item = offset % 32;
2366 
2367 		assert(offset < sizeof(sc->rtsregs.intrreg));
2368 
2369 		p = &sc->rtsregs.intrreg.iman;
2370 		p += item / sizeof(uint32_t);
2371 		value = *p;
2372 	}
2373 
2374 	DPRINTF(("pci_xhci: rtsregs read offset 0x%lx -> 0x%x\r\n",
2375 	        offset, value));
2376 
2377 	return (value);
2378 }
2379 
2380 static uint64_t
2381 pci_xhci_xecp_read(struct pci_xhci_softc *sc, uint64_t offset)
2382 {
2383 	uint32_t	value;
2384 
2385 	offset -= sc->regsend;
2386 	value = 0;
2387 
2388 	switch (offset) {
2389 	case 0:
2390 		/* rev major | rev minor | next-cap | cap-id */
2391 		value = (0x02 << 24) | (4 << 8) | XHCI_ID_PROTOCOLS;
2392 		break;
2393 	case 4:
2394 		/* name string = "USB" */
2395 		value = 0x20425355;
2396 		break;
2397 	case 8:
2398 		/* psic | proto-defined | compat # | compat offset */
2399 		value = ((XHCI_MAX_DEVS/2) << 8) | sc->usb2_port_start;
2400 		break;
2401 	case 12:
2402 		break;
2403 	case 16:
2404 		/* rev major | rev minor | next-cap | cap-id */
2405 		value = (0x03 << 24) | XHCI_ID_PROTOCOLS;
2406 		break;
2407 	case 20:
2408 		/* name string = "USB" */
2409 		value = 0x20425355;
2410 		break;
2411 	case 24:
2412 		/* psic | proto-defined | compat # | compat offset */
2413 		value = ((XHCI_MAX_DEVS/2) << 8) | sc->usb3_port_start;
2414 		break;
2415 	case 28:
2416 		break;
2417 	default:
2418 		DPRINTF(("pci_xhci: xecp invalid offset 0x%lx\r\n", offset));
2419 		break;
2420 	}
2421 
2422 	DPRINTF(("pci_xhci: xecp read offset 0x%lx -> 0x%x\r\n",
2423 	        offset, value));
2424 
2425 	return (value);
2426 }
2427 
2428 
2429 static uint64_t
2430 pci_xhci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2431     uint64_t offset, int size)
2432 {
2433 	struct pci_xhci_softc *sc;
2434 	uint32_t	value;
2435 
2436 	sc = pi->pi_arg;
2437 
2438 	assert(baridx == 0);
2439 
2440 	pthread_mutex_lock(&sc->mtx);
2441 	if (offset < XHCI_CAPLEN)
2442 		value = pci_xhci_hostcap_read(sc, offset);
2443 	else if (offset < sc->dboff)
2444 		value = pci_xhci_hostop_read(sc, offset);
2445 	else if (offset < sc->rtsoff)
2446 		value = pci_xhci_dbregs_read(sc, offset);
2447 	else if (offset < sc->regsend)
2448 		value = pci_xhci_rtsregs_read(sc, offset);
2449 	else if (offset < (sc->regsend + 4*32))
2450 		value = pci_xhci_xecp_read(sc, offset);
2451 	else {
2452 		value = 0;
2453 		WPRINTF(("pci_xhci: read invalid offset %ld\r\n", offset));
2454 	}
2455 
2456 	pthread_mutex_unlock(&sc->mtx);
2457 
2458 	switch (size) {
2459 	case 1:
2460 		value &= 0xFF;
2461 		break;
2462 	case 2:
2463 		value &= 0xFFFF;
2464 		break;
2465 	case 4:
2466 		value &= 0xFFFFFFFF;
2467 		break;
2468 	}
2469 
2470 	return (value);
2471 }
2472 
2473 static void
2474 pci_xhci_reset_port(struct pci_xhci_softc *sc, int portn, int warm)
2475 {
2476 	struct pci_xhci_portregs *port;
2477 	struct pci_xhci_dev_emu	*dev;
2478 	struct xhci_trb		evtrb;
2479 	int	error;
2480 
2481 	assert(portn <= XHCI_MAX_DEVS);
2482 
2483 	DPRINTF(("xhci reset port %d\r\n", portn));
2484 
2485 	port = XHCI_PORTREG_PTR(sc, portn);
2486 	dev = XHCI_DEVINST_PTR(sc, portn);
2487 	if (dev) {
2488 		port->portsc &= ~(XHCI_PS_PLS_MASK | XHCI_PS_PR | XHCI_PS_PRC);
2489 		port->portsc |= XHCI_PS_PED |
2490 		    XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2491 
2492 		if (warm && dev->dev_ue->ue_usbver == 3) {
2493 			port->portsc |= XHCI_PS_WRC;
2494 		}
2495 
2496 		if ((port->portsc & XHCI_PS_PRC) == 0) {
2497 			port->portsc |= XHCI_PS_PRC;
2498 
2499 			pci_xhci_set_evtrb(&evtrb, portn,
2500 			     XHCI_TRB_ERROR_SUCCESS,
2501 			     XHCI_TRB_EVENT_PORT_STS_CHANGE);
2502 			error = pci_xhci_insert_event(sc, &evtrb, 1);
2503 			if (error != XHCI_TRB_ERROR_SUCCESS)
2504 				DPRINTF(("xhci reset port insert event "
2505 				         "failed\r\n"));
2506 		}
2507 	}
2508 }
2509 
2510 static void
2511 pci_xhci_init_port(struct pci_xhci_softc *sc, int portn)
2512 {
2513 	struct pci_xhci_portregs *port;
2514 	struct pci_xhci_dev_emu	*dev;
2515 
2516 	port = XHCI_PORTREG_PTR(sc, portn);
2517 	dev = XHCI_DEVINST_PTR(sc, portn);
2518 	if (dev) {
2519 		port->portsc = XHCI_PS_CCS |		/* connected */
2520 		               XHCI_PS_PP;		/* port power */
2521 
2522 		if (dev->dev_ue->ue_usbver == 2) {
2523 			port->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_POLL) |
2524 		               XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2525 		} else {
2526 			port->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_U0) |
2527 		               XHCI_PS_PED |		/* enabled */
2528 		               XHCI_PS_SPEED_SET(dev->dev_ue->ue_usbspeed);
2529 		}
2530 
2531 		DPRINTF(("Init port %d 0x%x\n", portn, port->portsc));
2532 	} else {
2533 		port->portsc = XHCI_PS_PLS_SET(UPS_PORT_LS_RX_DET) | XHCI_PS_PP;
2534 		DPRINTF(("Init empty port %d 0x%x\n", portn, port->portsc));
2535 	}
2536 }
2537 
2538 static int
2539 pci_xhci_dev_intr(struct usb_hci *hci, int epctx)
2540 {
2541 	struct pci_xhci_dev_emu *dev;
2542 	struct xhci_dev_ctx	*dev_ctx;
2543 	struct xhci_trb		evtrb;
2544 	struct pci_xhci_softc	*sc;
2545 	struct pci_xhci_portregs *p;
2546 	struct xhci_endp_ctx	*ep_ctx;
2547 	int	error;
2548 	int	dir_in;
2549 	int	epid;
2550 
2551 	dir_in = epctx & 0x80;
2552 	epid = epctx & ~0x80;
2553 
2554 	/* HW endpoint contexts are 0-15; convert to epid based on dir */
2555 	epid = (epid * 2) + (dir_in ? 1 : 0);
2556 
2557 	assert(epid >= 1 && epid <= 31);
2558 
2559 	dev = hci->hci_sc;
2560 	sc = dev->xsc;
2561 
2562 	/* check if device is ready; OS has to initialise it */
2563 	if (sc->rtsregs.erstba_p == NULL ||
2564 	    (sc->opregs.usbcmd & XHCI_CMD_RS) == 0 ||
2565 	    dev->dev_ctx == NULL)
2566 		return (0);
2567 
2568 	p = XHCI_PORTREG_PTR(sc, hci->hci_port);
2569 
2570 	/* raise event if link U3 (suspended) state */
2571 	if (XHCI_PS_PLS_GET(p->portsc) == 3) {
2572 		p->portsc &= ~XHCI_PS_PLS_MASK;
2573 		p->portsc |= XHCI_PS_PLS_SET(UPS_PORT_LS_RESUME);
2574 		if ((p->portsc & XHCI_PS_PLC) != 0)
2575 			return (0);
2576 
2577 		p->portsc |= XHCI_PS_PLC;
2578 
2579 		pci_xhci_set_evtrb(&evtrb, hci->hci_port,
2580 		      XHCI_TRB_ERROR_SUCCESS, XHCI_TRB_EVENT_PORT_STS_CHANGE);
2581 		error = pci_xhci_insert_event(sc, &evtrb, 0);
2582 		if (error != XHCI_TRB_ERROR_SUCCESS)
2583 			goto done;
2584 	}
2585 
2586 	dev_ctx = dev->dev_ctx;
2587 	ep_ctx = &dev_ctx->ctx_ep[epid];
2588 	if ((ep_ctx->dwEpCtx0 & 0x7) == XHCI_ST_EPCTX_DISABLED) {
2589 		DPRINTF(("xhci device interrupt on disabled endpoint %d\r\n",
2590 		         epid));
2591 		return (0);
2592 	}
2593 
2594 	DPRINTF(("xhci device interrupt on endpoint %d\r\n", epid));
2595 
2596 	pci_xhci_device_doorbell(sc, hci->hci_port, epid, 0);
2597 
2598 done:
2599 	return (error);
2600 }
2601 
2602 static int
2603 pci_xhci_dev_event(struct usb_hci *hci, enum hci_usbev evid, void *param)
2604 {
2605 
2606 	DPRINTF(("xhci device event port %d\r\n", hci->hci_port));
2607 	return (0);
2608 }
2609 
2610 
2611 
2612 static void
2613 pci_xhci_device_usage(char *opt)
2614 {
2615 
2616 	fprintf(stderr, "Invalid USB emulation \"%s\"\r\n", opt);
2617 }
2618 
2619 static int
2620 pci_xhci_parse_opts(struct pci_xhci_softc *sc, char *opts)
2621 {
2622 	struct pci_xhci_dev_emu	**devices;
2623 	struct pci_xhci_dev_emu	*dev;
2624 	struct usb_devemu	*ue;
2625 	void	*devsc;
2626 	char	*uopt, *xopts, *config;
2627 	int	usb3_port, usb2_port, i;
2628 
2629 	usb3_port = sc->usb3_port_start - 1;
2630 	usb2_port = sc->usb2_port_start - 1;
2631 	devices = NULL;
2632 
2633 	if (opts == NULL)
2634 		goto portsfinal;
2635 
2636 	devices = calloc(XHCI_MAX_DEVS, sizeof(struct pci_xhci_dev_emu *));
2637 
2638 	sc->slots = calloc(XHCI_MAX_SLOTS, sizeof(struct pci_xhci_dev_emu *));
2639 	sc->devices = devices;
2640 	sc->ndevices = 0;
2641 
2642 	uopt = strdup(opts);
2643 	for (xopts = strtok(uopt, ",");
2644 	     xopts != NULL;
2645 	     xopts = strtok(NULL, ",")) {
2646 		if (usb2_port == ((sc->usb2_port_start-1) + XHCI_MAX_DEVS/2) ||
2647 		    usb3_port == ((sc->usb3_port_start-1) + XHCI_MAX_DEVS/2)) {
2648 			WPRINTF(("pci_xhci max number of USB 2 or 3 "
2649 			     "devices reached, max %d\r\n", XHCI_MAX_DEVS/2));
2650 			usb2_port = usb3_port = -1;
2651 			goto done;
2652 		}
2653 
2654 		/* device[=<config>] */
2655 		if ((config = strchr(xopts, '=')) == NULL)
2656 			config = "";		/* no config */
2657 		else
2658 			*config++ = '\0';
2659 
2660 		ue = usb_emu_finddev(xopts);
2661 		if (ue == NULL) {
2662 			pci_xhci_device_usage(xopts);
2663 			DPRINTF(("pci_xhci device not found %s\r\n", xopts));
2664 			usb2_port = usb3_port = -1;
2665 			goto done;
2666 		}
2667 
2668 		DPRINTF(("pci_xhci adding device %s, opts \"%s\"\r\n",
2669 		        xopts, config));
2670 
2671 		dev = calloc(1, sizeof(struct pci_xhci_dev_emu));
2672 		dev->xsc = sc;
2673 		dev->hci.hci_sc = dev;
2674 		dev->hci.hci_intr = pci_xhci_dev_intr;
2675 		dev->hci.hci_event = pci_xhci_dev_event;
2676 
2677 		if (ue->ue_usbver == 2) {
2678 			dev->hci.hci_port = usb2_port + 1;
2679 			devices[usb2_port] = dev;
2680 			usb2_port++;
2681 		} else {
2682 			dev->hci.hci_port = usb3_port + 1;
2683 			devices[usb3_port] = dev;
2684 			usb3_port++;
2685 		}
2686 
2687 		dev->hci.hci_address = 0;
2688 		devsc = ue->ue_init(&dev->hci, config);
2689 		if (devsc == NULL) {
2690 			pci_xhci_device_usage(xopts);
2691 			usb2_port = usb3_port = -1;
2692 			goto done;
2693 		}
2694 
2695 		dev->dev_ue = ue;
2696 		dev->dev_sc = devsc;
2697 
2698 		/* assign slot number to device */
2699 		sc->slots[sc->ndevices] = dev;
2700 
2701 		sc->ndevices++;
2702 	}
2703 
2704 portsfinal:
2705 	sc->portregs = calloc(XHCI_MAX_DEVS, sizeof(struct pci_xhci_portregs));
2706 
2707 	if (sc->ndevices > 0) {
2708 		/* port and slot numbering start from 1 */
2709 		sc->devices--;
2710 		sc->portregs--;
2711 		sc->slots--;
2712 
2713 		for (i = 1; i <= XHCI_MAX_DEVS; i++) {
2714 			pci_xhci_init_port(sc, i);
2715 		}
2716 	} else {
2717 		WPRINTF(("pci_xhci no USB devices configured\r\n"));
2718 		sc->ndevices = 1;
2719 	}
2720 
2721 done:
2722 	if (devices != NULL) {
2723 		if (usb2_port <= 0 && usb3_port <= 0) {
2724 			sc->devices = NULL;
2725 			for (i = 0; devices[i] != NULL; i++)
2726 				free(devices[i]);
2727 			sc->ndevices = -1;
2728 
2729 			free(devices);
2730 		}
2731 	}
2732 	return (sc->ndevices);
2733 }
2734 
2735 static int
2736 pci_xhci_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2737 {
2738 	struct pci_xhci_softc *sc;
2739 	int	error;
2740 
2741 	if (xhci_in_use) {
2742 		WPRINTF(("pci_xhci controller already defined\r\n"));
2743 		return (-1);
2744 	}
2745 	xhci_in_use = 1;
2746 
2747 	sc = calloc(1, sizeof(struct pci_xhci_softc));
2748 	pi->pi_arg = sc;
2749 	sc->xsc_pi = pi;
2750 
2751 	sc->usb2_port_start = (XHCI_MAX_DEVS/2) + 1;
2752 	sc->usb3_port_start = 1;
2753 
2754 	/* discover devices */
2755 	error = pci_xhci_parse_opts(sc, opts);
2756 	if (error < 0)
2757 		goto done;
2758 	else
2759 		error = 0;
2760 
2761 	sc->caplength = XHCI_SET_CAPLEN(XHCI_CAPLEN) |
2762 	                XHCI_SET_HCIVERSION(0x0100);
2763 	sc->hcsparams1 = XHCI_SET_HCSP1_MAXPORTS(XHCI_MAX_DEVS) |
2764 	                 XHCI_SET_HCSP1_MAXINTR(1) |	/* interrupters */
2765 	                 XHCI_SET_HCSP1_MAXSLOTS(XHCI_MAX_SLOTS);
2766 	sc->hcsparams2 = XHCI_SET_HCSP2_ERSTMAX(XHCI_ERST_MAX) |
2767 	                 XHCI_SET_HCSP2_IST(0x04);
2768 	sc->hcsparams3 = 0;				/* no latency */
2769 	sc->hccparams1 = XHCI_SET_HCCP1_NSS(1) |	/* no 2nd-streams */
2770 	                 XHCI_SET_HCCP1_SPC(1) |	/* short packet */
2771 	                 XHCI_SET_HCCP1_MAXPSA(XHCI_STREAMS_MAX);
2772 	sc->hccparams2 = XHCI_SET_HCCP2_LEC(1) |
2773 	                 XHCI_SET_HCCP2_U3C(1);
2774 	sc->dboff = XHCI_SET_DOORBELL(XHCI_CAPLEN + XHCI_PORTREGS_START +
2775 	            XHCI_MAX_DEVS * sizeof(struct pci_xhci_portregs));
2776 
2777 	/* dboff must be 32-bit aligned */
2778 	if (sc->dboff & 0x3)
2779 		sc->dboff = (sc->dboff + 0x3) & ~0x3;
2780 
2781 	/* rtsoff must be 32-bytes aligned */
2782 	sc->rtsoff = XHCI_SET_RTSOFFSET(sc->dboff + (XHCI_MAX_SLOTS+1) * 32);
2783 	if (sc->rtsoff & 0x1F)
2784 		sc->rtsoff = (sc->rtsoff + 0x1F) & ~0x1F;
2785 
2786 	DPRINTF(("pci_xhci dboff: 0x%x, rtsoff: 0x%x\r\n", sc->dboff,
2787 	        sc->rtsoff));
2788 
2789 	sc->opregs.usbsts = XHCI_STS_HCH;
2790 	sc->opregs.pgsz = XHCI_PAGESIZE_4K;
2791 
2792 	pci_xhci_reset(sc);
2793 
2794 	sc->regsend = sc->rtsoff + 0x20 + 32;		/* only 1 intrpter */
2795 
2796 	/*
2797 	 * Set extended capabilities pointer to be after regsend;
2798 	 * value of xecp field is 32-bit offset.
2799 	 */
2800 	sc->hccparams1 |= XHCI_SET_HCCP1_XECP(sc->regsend/4);
2801 
2802 	pci_set_cfgdata16(pi, PCIR_DEVICE, 0x1E31);
2803 	pci_set_cfgdata16(pi, PCIR_VENDOR, 0x8086);
2804 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_SERIALBUS);
2805 	pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_SERIALBUS_USB);
2806 	pci_set_cfgdata8(pi, PCIR_PROGIF,PCIP_SERIALBUS_USB_XHCI);
2807 	pci_set_cfgdata8(pi, PCI_USBREV, PCI_USB_REV_3_0);
2808 
2809 	pci_emul_add_msicap(pi, 1);
2810 
2811 	/* regsend + xecp registers */
2812 	pci_emul_alloc_bar(pi, 0, PCIBAR_MEM32, sc->regsend + 4*32);
2813 	DPRINTF(("pci_xhci pci_emu_alloc: %d\r\n", sc->regsend + 4*32));
2814 
2815 
2816 	pci_lintr_request(pi);
2817 
2818 	pthread_mutex_init(&sc->mtx, NULL);
2819 
2820 done:
2821 	if (error) {
2822 		free(sc);
2823 	}
2824 
2825 	return (error);
2826 }
2827 
2828 
2829 
2830 struct pci_devemu pci_de_xhci = {
2831 	.pe_emu =	"xhci",
2832 	.pe_init =	pci_xhci_init,
2833 	.pe_barwrite =	pci_xhci_write,
2834 	.pe_barread =	pci_xhci_read
2835 };
2836 PCI_EMUL_SET(pci_de_xhci);
2837