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