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