xref: /freebsd/sys/dev/usb/controller/xhci.c (revision 243e928310d073338c5ec089f0dce238a80b9866)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * USB eXtensible Host Controller Interface, a.k.a. USB 3.0 controller.
29  *
30  * The XHCI 1.0 spec can be found at
31  * http://www.intel.com/technology/usb/download/xHCI_Specification_for_USB.pdf
32  * and the USB 3.0 spec at
33  * http://www.usb.org/developers/docs/usb_30_spec_060910.zip
34  */
35 
36 /*
37  * A few words about the design implementation: This driver emulates
38  * the concept about TDs which is found in EHCI specification. This
39  * way we achieve that the USB controller drivers look similar to
40  * eachother which makes it easier to understand the code.
41  */
42 
43 #ifdef USB_GLOBAL_INCLUDE_FILE
44 #include USB_GLOBAL_INCLUDE_FILE
45 #else
46 #include <sys/stdint.h>
47 #include <sys/stddef.h>
48 #include <sys/param.h>
49 #include <sys/queue.h>
50 #include <sys/types.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/bus.h>
54 #include <sys/module.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/sx.h>
60 #include <sys/unistd.h>
61 #include <sys/callout.h>
62 #include <sys/malloc.h>
63 #include <sys/priv.h>
64 
65 #include <dev/usb/usb.h>
66 #include <dev/usb/usbdi.h>
67 
68 #define	USB_DEBUG_VAR xhcidebug
69 
70 #include <dev/usb/usb_core.h>
71 #include <dev/usb/usb_debug.h>
72 #include <dev/usb/usb_busdma.h>
73 #include <dev/usb/usb_process.h>
74 #include <dev/usb/usb_transfer.h>
75 #include <dev/usb/usb_device.h>
76 #include <dev/usb/usb_hub.h>
77 #include <dev/usb/usb_util.h>
78 
79 #include <dev/usb/usb_controller.h>
80 #include <dev/usb/usb_bus.h>
81 #endif			/* USB_GLOBAL_INCLUDE_FILE */
82 
83 #include <dev/usb/controller/xhci.h>
84 #include <dev/usb/controller/xhcireg.h>
85 
86 #define	XHCI_BUS2SC(bus) \
87    ((struct xhci_softc *)(((uint8_t *)(bus)) - \
88     ((uint8_t *)&(((struct xhci_softc *)0)->sc_bus))))
89 
90 static SYSCTL_NODE(_hw_usb, OID_AUTO, xhci, CTLFLAG_RW, 0, "USB XHCI");
91 
92 static int xhcistreams;
93 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, streams, CTLFLAG_RWTUN,
94     &xhcistreams, 0, "Set to enable streams mode support");
95 
96 #ifdef USB_DEBUG
97 static int xhcidebug;
98 static int xhciroute;
99 static int xhcipolling;
100 static int xhcidma32;
101 
102 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, debug, CTLFLAG_RWTUN,
103     &xhcidebug, 0, "Debug level");
104 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, xhci_port_route, CTLFLAG_RWTUN,
105     &xhciroute, 0, "Routing bitmap for switching EHCI ports to the XHCI controller");
106 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, use_polling, CTLFLAG_RWTUN,
107     &xhcipolling, 0, "Set to enable software interrupt polling for the XHCI controller");
108 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, dma32, CTLFLAG_RWTUN,
109     &xhcidma32, 0, "Set to only use 32-bit DMA for the XHCI controller");
110 #else
111 #define	xhciroute 0
112 #define	xhcidma32 0
113 #endif
114 
115 #define	XHCI_INTR_ENDPT 1
116 
117 struct xhci_std_temp {
118 	struct xhci_softc	*sc;
119 	struct usb_page_cache	*pc;
120 	struct xhci_td		*td;
121 	struct xhci_td		*td_next;
122 	uint32_t		len;
123 	uint32_t		offset;
124 	uint32_t		max_packet_size;
125 	uint32_t		average;
126 	uint16_t		isoc_delta;
127 	uint16_t		isoc_frame;
128 	uint8_t			shortpkt;
129 	uint8_t			multishort;
130 	uint8_t			last_frame;
131 	uint8_t			trb_type;
132 	uint8_t			direction;
133 	uint8_t			tbc;
134 	uint8_t			tlbpc;
135 	uint8_t			step_td;
136 	uint8_t			do_isoc_sync;
137 };
138 
139 static void	xhci_do_poll(struct usb_bus *);
140 static void	xhci_device_done(struct usb_xfer *, usb_error_t);
141 static void	xhci_root_intr(struct xhci_softc *);
142 static void	xhci_free_device_ext(struct usb_device *);
143 static struct xhci_endpoint_ext *xhci_get_endpoint_ext(struct usb_device *,
144 		    struct usb_endpoint_descriptor *);
145 static usb_proc_callback_t xhci_configure_msg;
146 static usb_error_t xhci_configure_device(struct usb_device *);
147 static usb_error_t xhci_configure_endpoint(struct usb_device *,
148 		   struct usb_endpoint_descriptor *, struct xhci_endpoint_ext *,
149 		   uint16_t, uint8_t, uint8_t, uint8_t, uint16_t, uint16_t,
150 		   uint8_t);
151 static usb_error_t xhci_configure_mask(struct usb_device *,
152 		    uint32_t, uint8_t);
153 static usb_error_t xhci_cmd_evaluate_ctx(struct xhci_softc *,
154 		    uint64_t, uint8_t);
155 static void xhci_endpoint_doorbell(struct usb_xfer *);
156 static void xhci_ctx_set_le32(struct xhci_softc *sc, volatile uint32_t *ptr, uint32_t val);
157 static uint32_t xhci_ctx_get_le32(struct xhci_softc *sc, volatile uint32_t *ptr);
158 static void xhci_ctx_set_le64(struct xhci_softc *sc, volatile uint64_t *ptr, uint64_t val);
159 #ifdef USB_DEBUG
160 static uint64_t xhci_ctx_get_le64(struct xhci_softc *sc, volatile uint64_t *ptr);
161 #endif
162 
163 static const struct usb_bus_methods xhci_bus_methods;
164 
165 #ifdef USB_DEBUG
166 static void
167 xhci_dump_trb(struct xhci_trb *trb)
168 {
169 	DPRINTFN(5, "trb = %p\n", trb);
170 	DPRINTFN(5, "qwTrb0 = 0x%016llx\n", (long long)le64toh(trb->qwTrb0));
171 	DPRINTFN(5, "dwTrb2 = 0x%08x\n", le32toh(trb->dwTrb2));
172 	DPRINTFN(5, "dwTrb3 = 0x%08x\n", le32toh(trb->dwTrb3));
173 }
174 
175 static void
176 xhci_dump_endpoint(struct xhci_softc *sc, struct xhci_endp_ctx *pep)
177 {
178 	DPRINTFN(5, "pep = %p\n", pep);
179 	DPRINTFN(5, "dwEpCtx0=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx0));
180 	DPRINTFN(5, "dwEpCtx1=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx1));
181 	DPRINTFN(5, "qwEpCtx2=0x%016llx\n", (long long)xhci_ctx_get_le64(sc, &pep->qwEpCtx2));
182 	DPRINTFN(5, "dwEpCtx4=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx4));
183 	DPRINTFN(5, "dwEpCtx5=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx5));
184 	DPRINTFN(5, "dwEpCtx6=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx6));
185 	DPRINTFN(5, "dwEpCtx7=0x%08x\n", xhci_ctx_get_le32(sc, &pep->dwEpCtx7));
186 }
187 
188 static void
189 xhci_dump_device(struct xhci_softc *sc, struct xhci_slot_ctx *psl)
190 {
191 	DPRINTFN(5, "psl = %p\n", psl);
192 	DPRINTFN(5, "dwSctx0=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx0));
193 	DPRINTFN(5, "dwSctx1=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx1));
194 	DPRINTFN(5, "dwSctx2=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx2));
195 	DPRINTFN(5, "dwSctx3=0x%08x\n", xhci_ctx_get_le32(sc, &psl->dwSctx3));
196 }
197 #endif
198 
199 uint8_t
200 xhci_use_polling(void)
201 {
202 #ifdef USB_DEBUG
203 	return (xhcipolling != 0);
204 #else
205 	return (0);
206 #endif
207 }
208 
209 static void
210 xhci_iterate_hw_softc(struct usb_bus *bus, usb_bus_mem_sub_cb_t *cb)
211 {
212 	struct xhci_softc *sc = XHCI_BUS2SC(bus);
213 	uint8_t i;
214 
215 	cb(bus, &sc->sc_hw.root_pc, &sc->sc_hw.root_pg,
216 	   sizeof(struct xhci_hw_root), XHCI_PAGE_SIZE);
217 
218 	cb(bus, &sc->sc_hw.ctx_pc, &sc->sc_hw.ctx_pg,
219 	   sizeof(struct xhci_dev_ctx_addr), XHCI_PAGE_SIZE);
220 
221 	for (i = 0; i != XHCI_MAX_SCRATCHPADS; i++) {
222 		cb(bus, &sc->sc_hw.scratch_pc[i], &sc->sc_hw.scratch_pg[i],
223 		    XHCI_PAGE_SIZE, XHCI_PAGE_SIZE);
224 	}
225 }
226 
227 static void
228 xhci_ctx_set_le32(struct xhci_softc *sc, volatile uint32_t *ptr, uint32_t val)
229 {
230 	if (sc->sc_ctx_is_64_byte) {
231 		uint32_t offset;
232 		/* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
233 		/* all contexts are initially 32-bytes */
234 		offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
235 		ptr = (volatile uint32_t *)(((volatile uint8_t *)ptr) + offset);
236 	}
237 	*ptr = htole32(val);
238 }
239 
240 static uint32_t
241 xhci_ctx_get_le32(struct xhci_softc *sc, volatile uint32_t *ptr)
242 {
243 	if (sc->sc_ctx_is_64_byte) {
244 		uint32_t offset;
245 		/* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
246 		/* all contexts are initially 32-bytes */
247 		offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
248 		ptr = (volatile uint32_t *)(((volatile uint8_t *)ptr) + offset);
249 	}
250 	return (le32toh(*ptr));
251 }
252 
253 static void
254 xhci_ctx_set_le64(struct xhci_softc *sc, volatile uint64_t *ptr, uint64_t val)
255 {
256 	if (sc->sc_ctx_is_64_byte) {
257 		uint32_t offset;
258 		/* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
259 		/* all contexts are initially 32-bytes */
260 		offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
261 		ptr = (volatile uint64_t *)(((volatile uint8_t *)ptr) + offset);
262 	}
263 	*ptr = htole64(val);
264 }
265 
266 #ifdef USB_DEBUG
267 static uint64_t
268 xhci_ctx_get_le64(struct xhci_softc *sc, volatile uint64_t *ptr)
269 {
270 	if (sc->sc_ctx_is_64_byte) {
271 		uint32_t offset;
272 		/* exploit the fact that our structures are XHCI_PAGE_SIZE aligned */
273 		/* all contexts are initially 32-bytes */
274 		offset = ((uintptr_t)ptr) & ((XHCI_PAGE_SIZE - 1) & ~(31U));
275 		ptr = (volatile uint64_t *)(((volatile uint8_t *)ptr) + offset);
276 	}
277 	return (le64toh(*ptr));
278 }
279 #endif
280 
281 static int
282 xhci_reset_command_queue_locked(struct xhci_softc *sc)
283 {
284 	struct usb_page_search buf_res;
285 	struct xhci_hw_root *phwr;
286 	uint64_t addr;
287 	uint32_t temp;
288 
289 	DPRINTF("\n");
290 
291 	temp = XREAD4(sc, oper, XHCI_CRCR_LO);
292 	if (temp & XHCI_CRCR_LO_CRR) {
293 		DPRINTF("Command ring running\n");
294 		temp &= ~(XHCI_CRCR_LO_CS | XHCI_CRCR_LO_CA);
295 
296 		/*
297 		 * Try to abort the last command as per section
298 		 * 4.6.1.2 "Aborting a Command" of the XHCI
299 		 * specification:
300 		 */
301 
302 		/* stop and cancel */
303 		XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CS);
304 		XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
305 
306 		XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CA);
307 		XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
308 
309  		/* wait 250ms */
310  		usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 4);
311 
312 		/* check if command ring is still running */
313 		temp = XREAD4(sc, oper, XHCI_CRCR_LO);
314 		if (temp & XHCI_CRCR_LO_CRR) {
315 			DPRINTF("Comand ring still running\n");
316 			return (USB_ERR_IOERROR);
317 		}
318 	}
319 
320 	/* reset command ring */
321 	sc->sc_command_ccs = 1;
322 	sc->sc_command_idx = 0;
323 
324 	usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
325 
326 	/* set up command ring control base address */
327 	addr = buf_res.physaddr;
328 	phwr = buf_res.buffer;
329 	addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[0];
330 
331 	DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
332 
333 	memset(phwr->hwr_commands, 0, sizeof(phwr->hwr_commands));
334 	phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
335 
336 	usb_pc_cpu_flush(&sc->sc_hw.root_pc);
337 
338 	XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
339 	XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
340 
341 	return (0);
342 }
343 
344 usb_error_t
345 xhci_start_controller(struct xhci_softc *sc)
346 {
347 	struct usb_page_search buf_res;
348 	struct xhci_hw_root *phwr;
349 	struct xhci_dev_ctx_addr *pdctxa;
350 	uint64_t addr;
351 	uint32_t temp;
352 	uint16_t i;
353 
354 	DPRINTF("\n");
355 
356 	sc->sc_event_ccs = 1;
357 	sc->sc_event_idx = 0;
358 	sc->sc_command_ccs = 1;
359 	sc->sc_command_idx = 0;
360 
361 	/* Reset controller */
362 	XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_HCRST);
363 
364 	for (i = 0; i != 100; i++) {
365 		usb_pause_mtx(NULL, hz / 100);
366 		temp = (XREAD4(sc, oper, XHCI_USBCMD) & XHCI_CMD_HCRST) |
367 		    (XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_CNR);
368 		if (!temp)
369 			break;
370 	}
371 
372 	if (temp) {
373 		device_printf(sc->sc_bus.parent, "Controller "
374 		    "reset timeout.\n");
375 		return (USB_ERR_IOERROR);
376 	}
377 
378 	/* set up number of device slots */
379 	DPRINTF("CONFIG=0x%08x -> 0x%08x\n",
380 	    XREAD4(sc, oper, XHCI_CONFIG), sc->sc_noslot);
381 
382 	XWRITE4(sc, oper, XHCI_CONFIG, sc->sc_noslot);
383 
384 	temp = XREAD4(sc, oper, XHCI_USBSTS);
385 
386 	/* clear interrupts */
387 	XWRITE4(sc, oper, XHCI_USBSTS, temp);
388 	/* disable all device notifications */
389 	XWRITE4(sc, oper, XHCI_DNCTRL, 0);
390 
391 	/* set up device context base address */
392 	usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
393 	pdctxa = buf_res.buffer;
394 	memset(pdctxa, 0, sizeof(*pdctxa));
395 
396 	addr = buf_res.physaddr;
397 	addr += (uintptr_t)&((struct xhci_dev_ctx_addr *)0)->qwSpBufPtr[0];
398 
399 	/* slot 0 points to the table of scratchpad pointers */
400 	pdctxa->qwBaaDevCtxAddr[0] = htole64(addr);
401 
402 	for (i = 0; i != sc->sc_noscratch; i++) {
403 		struct usb_page_search buf_scp;
404 		usbd_get_page(&sc->sc_hw.scratch_pc[i], 0, &buf_scp);
405 		pdctxa->qwSpBufPtr[i] = htole64((uint64_t)buf_scp.physaddr);
406 	}
407 
408 	addr = buf_res.physaddr;
409 
410 	XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
411 	XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
412 	XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
413 	XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
414 
415 	/* set up event table size */
416 	DPRINTF("ERSTSZ=0x%08x -> 0x%08x\n",
417 	    XREAD4(sc, runt, XHCI_ERSTSZ(0)), sc->sc_erst_max);
418 
419 	XWRITE4(sc, runt, XHCI_ERSTSZ(0), XHCI_ERSTS_SET(sc->sc_erst_max));
420 
421 	/* set up interrupt rate */
422 	XWRITE4(sc, runt, XHCI_IMOD(0), sc->sc_imod_default);
423 
424 	usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
425 
426 	phwr = buf_res.buffer;
427 	addr = buf_res.physaddr;
428 	addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_events[0];
429 
430 	/* reset hardware root structure */
431 	memset(phwr, 0, sizeof(*phwr));
432 
433 	phwr->hwr_ring_seg[0].qwEvrsTablePtr = htole64(addr);
434 	phwr->hwr_ring_seg[0].dwEvrsTableSize = htole32(XHCI_MAX_EVENTS);
435 
436 	DPRINTF("ERDP(0)=0x%016llx\n", (unsigned long long)addr);
437 
438 	XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
439 	XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
440 
441 	addr = buf_res.physaddr;
442 
443 	DPRINTF("ERSTBA(0)=0x%016llx\n", (unsigned long long)addr);
444 
445 	XWRITE4(sc, runt, XHCI_ERSTBA_LO(0), (uint32_t)addr);
446 	XWRITE4(sc, runt, XHCI_ERSTBA_HI(0), (uint32_t)(addr >> 32));
447 
448 	/* set up interrupter registers */
449 	temp = XREAD4(sc, runt, XHCI_IMAN(0));
450 	temp |= XHCI_IMAN_INTR_ENA;
451 	XWRITE4(sc, runt, XHCI_IMAN(0), temp);
452 
453 	/* set up command ring control base address */
454 	addr = buf_res.physaddr;
455 	addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[0];
456 
457 	DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
458 
459 	XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
460 	XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
461 
462 	phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
463 
464 	usb_bus_mem_flush_all(&sc->sc_bus, &xhci_iterate_hw_softc);
465 
466 	/* Go! */
467 	XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_RS |
468 	    XHCI_CMD_INTE | XHCI_CMD_HSEE);
469 
470 	for (i = 0; i != 100; i++) {
471 		usb_pause_mtx(NULL, hz / 100);
472 		temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
473 		if (!temp)
474 			break;
475 	}
476 	if (temp) {
477 		XWRITE4(sc, oper, XHCI_USBCMD, 0);
478 		device_printf(sc->sc_bus.parent, "Run timeout.\n");
479 		return (USB_ERR_IOERROR);
480 	}
481 
482 	/* catch any lost interrupts */
483 	xhci_do_poll(&sc->sc_bus);
484 
485 	if (sc->sc_port_route != NULL) {
486 		/* Route all ports to the XHCI by default */
487 		sc->sc_port_route(sc->sc_bus.parent,
488 		    ~xhciroute, xhciroute);
489 	}
490 	return (0);
491 }
492 
493 usb_error_t
494 xhci_halt_controller(struct xhci_softc *sc)
495 {
496 	uint32_t temp;
497 	uint16_t i;
498 
499 	DPRINTF("\n");
500 
501 	sc->sc_capa_off = 0;
502 	sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
503 	sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0xF;
504 	sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
505 
506 	/* Halt controller */
507 	XWRITE4(sc, oper, XHCI_USBCMD, 0);
508 
509 	for (i = 0; i != 100; i++) {
510 		usb_pause_mtx(NULL, hz / 100);
511 		temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
512 		if (temp)
513 			break;
514 	}
515 
516 	if (!temp) {
517 		device_printf(sc->sc_bus.parent, "Controller halt timeout.\n");
518 		return (USB_ERR_IOERROR);
519 	}
520 	return (0);
521 }
522 
523 usb_error_t
524 xhci_init(struct xhci_softc *sc, device_t self, uint8_t dma32)
525 {
526 	uint32_t temp;
527 
528 	DPRINTF("\n");
529 
530 	/* initialize some bus fields */
531 	sc->sc_bus.parent = self;
532 
533 	/* set the bus revision */
534 	sc->sc_bus.usbrev = USB_REV_3_0;
535 
536 	/* set up the bus struct */
537 	sc->sc_bus.methods = &xhci_bus_methods;
538 
539 	/* set up devices array */
540 	sc->sc_bus.devices = sc->sc_devices;
541 	sc->sc_bus.devices_max = XHCI_MAX_DEVICES;
542 
543 	/* set default cycle state in case of early interrupts */
544 	sc->sc_event_ccs = 1;
545 	sc->sc_command_ccs = 1;
546 
547 	/* set up bus space offsets */
548 	sc->sc_capa_off = 0;
549 	sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
550 	sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0x1F;
551 	sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
552 
553 	DPRINTF("CAPLENGTH=0x%x\n", sc->sc_oper_off);
554 	DPRINTF("RUNTIMEOFFSET=0x%x\n", sc->sc_runt_off);
555 	DPRINTF("DOOROFFSET=0x%x\n", sc->sc_door_off);
556 
557 	DPRINTF("xHCI version = 0x%04x\n", XREAD2(sc, capa, XHCI_HCIVERSION));
558 
559 	if (!(XREAD4(sc, oper, XHCI_PAGESIZE) & XHCI_PAGESIZE_4K)) {
560 		device_printf(sc->sc_bus.parent, "Controller does "
561 		    "not support 4K page size.\n");
562 		return (ENXIO);
563 	}
564 
565 	temp = XREAD4(sc, capa, XHCI_HCSPARAMS0);
566 
567 	DPRINTF("HCS0 = 0x%08x\n", temp);
568 
569 	/* set up context size */
570 	if (XHCI_HCS0_CSZ(temp)) {
571 		sc->sc_ctx_is_64_byte = 1;
572 	} else {
573 		sc->sc_ctx_is_64_byte = 0;
574 	}
575 
576 	/* get DMA bits */
577 	sc->sc_bus.dma_bits = (XHCI_HCS0_AC64(temp) &&
578 	    xhcidma32 == 0 && dma32 == 0) ? 64 : 32;
579 
580 	device_printf(self, "%d bytes context size, %d-bit DMA\n",
581 	    sc->sc_ctx_is_64_byte ? 64 : 32, (int)sc->sc_bus.dma_bits);
582 
583 	temp = XREAD4(sc, capa, XHCI_HCSPARAMS1);
584 
585 	/* get number of device slots */
586 	sc->sc_noport = XHCI_HCS1_N_PORTS(temp);
587 
588 	if (sc->sc_noport == 0) {
589 		device_printf(sc->sc_bus.parent, "Invalid number "
590 		    "of ports: %u\n", sc->sc_noport);
591 		return (ENXIO);
592 	}
593 
594 	sc->sc_noport = sc->sc_noport;
595 	sc->sc_noslot = XHCI_HCS1_DEVSLOT_MAX(temp);
596 
597 	DPRINTF("Max slots: %u\n", sc->sc_noslot);
598 
599 	if (sc->sc_noslot > XHCI_MAX_DEVICES)
600 		sc->sc_noslot = XHCI_MAX_DEVICES;
601 
602 	temp = XREAD4(sc, capa, XHCI_HCSPARAMS2);
603 
604 	DPRINTF("HCS2=0x%08x\n", temp);
605 
606 	/* get number of scratchpads */
607 	sc->sc_noscratch = XHCI_HCS2_SPB_MAX(temp);
608 
609 	if (sc->sc_noscratch > XHCI_MAX_SCRATCHPADS) {
610 		device_printf(sc->sc_bus.parent, "XHCI request "
611 		    "too many scratchpads\n");
612 		return (ENOMEM);
613 	}
614 
615 	DPRINTF("Max scratch: %u\n", sc->sc_noscratch);
616 
617 	/* get event table size */
618 	sc->sc_erst_max = 1U << XHCI_HCS2_ERST_MAX(temp);
619 	if (sc->sc_erst_max > XHCI_MAX_RSEG)
620 		sc->sc_erst_max = XHCI_MAX_RSEG;
621 
622 	temp = XREAD4(sc, capa, XHCI_HCSPARAMS3);
623 
624 	/* get maximum exit latency */
625 	sc->sc_exit_lat_max = XHCI_HCS3_U1_DEL(temp) +
626 	    XHCI_HCS3_U2_DEL(temp) + 250 /* us */;
627 
628 	/* Check if we should use the default IMOD value. */
629 	if (sc->sc_imod_default == 0)
630 		sc->sc_imod_default = XHCI_IMOD_DEFAULT;
631 
632 	/* get all DMA memory */
633 	if (usb_bus_mem_alloc_all(&sc->sc_bus,
634 	    USB_GET_DMA_TAG(self), &xhci_iterate_hw_softc)) {
635 		return (ENOMEM);
636 	}
637 
638 	/* set up command queue mutex and condition varible */
639 	cv_init(&sc->sc_cmd_cv, "CMDQ");
640 	sx_init(&sc->sc_cmd_sx, "CMDQ lock");
641 
642 	sc->sc_config_msg[0].hdr.pm_callback = &xhci_configure_msg;
643 	sc->sc_config_msg[0].bus = &sc->sc_bus;
644 	sc->sc_config_msg[1].hdr.pm_callback = &xhci_configure_msg;
645 	sc->sc_config_msg[1].bus = &sc->sc_bus;
646 
647 	return (0);
648 }
649 
650 void
651 xhci_uninit(struct xhci_softc *sc)
652 {
653 	/*
654 	 * NOTE: At this point the control transfer process is gone
655 	 * and "xhci_configure_msg" is no longer called. Consequently
656 	 * waiting for the configuration messages to complete is not
657 	 * needed.
658 	 */
659 	usb_bus_mem_free_all(&sc->sc_bus, &xhci_iterate_hw_softc);
660 
661 	cv_destroy(&sc->sc_cmd_cv);
662 	sx_destroy(&sc->sc_cmd_sx);
663 }
664 
665 static void
666 xhci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state)
667 {
668 	struct xhci_softc *sc = XHCI_BUS2SC(bus);
669 
670 	switch (state) {
671 	case USB_HW_POWER_SUSPEND:
672 		DPRINTF("Stopping the XHCI\n");
673 		xhci_halt_controller(sc);
674 		break;
675 	case USB_HW_POWER_SHUTDOWN:
676 		DPRINTF("Stopping the XHCI\n");
677 		xhci_halt_controller(sc);
678 		break;
679 	case USB_HW_POWER_RESUME:
680 		DPRINTF("Starting the XHCI\n");
681 		xhci_start_controller(sc);
682 		break;
683 	default:
684 		break;
685 	}
686 }
687 
688 static usb_error_t
689 xhci_generic_done_sub(struct usb_xfer *xfer)
690 {
691 	struct xhci_td *td;
692 	struct xhci_td *td_alt_next;
693 	uint32_t len;
694 	uint8_t status;
695 
696 	td = xfer->td_transfer_cache;
697 	td_alt_next = td->alt_next;
698 
699 	if (xfer->aframes != xfer->nframes)
700 		usbd_xfer_set_frame_len(xfer, xfer->aframes, 0);
701 
702 	while (1) {
703 
704 		usb_pc_cpu_invalidate(td->page_cache);
705 
706 		status = td->status;
707 		len = td->remainder;
708 
709 		DPRINTFN(4, "xfer=%p[%u/%u] rem=%u/%u status=%u\n",
710 		    xfer, (unsigned int)xfer->aframes,
711 		    (unsigned int)xfer->nframes,
712 		    (unsigned int)len, (unsigned int)td->len,
713 		    (unsigned int)status);
714 
715 		/*
716 	         * Verify the status length and
717 		 * add the length to "frlengths[]":
718 	         */
719 		if (len > td->len) {
720 			/* should not happen */
721 			DPRINTF("Invalid status length, "
722 			    "0x%04x/0x%04x bytes\n", len, td->len);
723 			status = XHCI_TRB_ERROR_LENGTH;
724 		} else if (xfer->aframes != xfer->nframes) {
725 			xfer->frlengths[xfer->aframes] += td->len - len;
726 		}
727 		/* Check for last transfer */
728 		if (((void *)td) == xfer->td_transfer_last) {
729 			td = NULL;
730 			break;
731 		}
732 		/* Check for transfer error */
733 		if (status != XHCI_TRB_ERROR_SHORT_PKT &&
734 		    status != XHCI_TRB_ERROR_SUCCESS) {
735 			/* the transfer is finished */
736 			td = NULL;
737 			break;
738 		}
739 		/* Check for short transfer */
740 		if (len > 0) {
741 			if (xfer->flags_int.short_frames_ok ||
742 			    xfer->flags_int.isochronous_xfr ||
743 			    xfer->flags_int.control_xfr) {
744 				/* follow alt next */
745 				td = td->alt_next;
746 			} else {
747 				/* the transfer is finished */
748 				td = NULL;
749 			}
750 			break;
751 		}
752 		td = td->obj_next;
753 
754 		if (td->alt_next != td_alt_next) {
755 			/* this USB frame is complete */
756 			break;
757 		}
758 	}
759 
760 	/* update transfer cache */
761 
762 	xfer->td_transfer_cache = td;
763 
764 	return ((status == XHCI_TRB_ERROR_STALL) ? USB_ERR_STALLED :
765 	    (status != XHCI_TRB_ERROR_SHORT_PKT &&
766 	    status != XHCI_TRB_ERROR_SUCCESS) ? USB_ERR_IOERROR :
767 	    USB_ERR_NORMAL_COMPLETION);
768 }
769 
770 static void
771 xhci_generic_done(struct usb_xfer *xfer)
772 {
773 	usb_error_t err = 0;
774 
775 	DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
776 	    xfer, xfer->endpoint);
777 
778 	/* reset scanner */
779 
780 	xfer->td_transfer_cache = xfer->td_transfer_first;
781 
782 	if (xfer->flags_int.control_xfr) {
783 
784 		if (xfer->flags_int.control_hdr)
785 			err = xhci_generic_done_sub(xfer);
786 
787 		xfer->aframes = 1;
788 
789 		if (xfer->td_transfer_cache == NULL)
790 			goto done;
791 	}
792 
793 	while (xfer->aframes != xfer->nframes) {
794 
795 		err = xhci_generic_done_sub(xfer);
796 		xfer->aframes++;
797 
798 		if (xfer->td_transfer_cache == NULL)
799 			goto done;
800 	}
801 
802 	if (xfer->flags_int.control_xfr &&
803 	    !xfer->flags_int.control_act)
804 		err = xhci_generic_done_sub(xfer);
805 done:
806 	/* transfer is complete */
807 	xhci_device_done(xfer, err);
808 }
809 
810 static void
811 xhci_activate_transfer(struct usb_xfer *xfer)
812 {
813 	struct xhci_td *td;
814 
815 	td = xfer->td_transfer_cache;
816 
817 	usb_pc_cpu_invalidate(td->page_cache);
818 
819 	if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
820 
821 		/* activate the transfer */
822 
823 		td->td_trb[0].dwTrb3 |= htole32(XHCI_TRB_3_CYCLE_BIT);
824 		usb_pc_cpu_flush(td->page_cache);
825 
826 		xhci_endpoint_doorbell(xfer);
827 	}
828 }
829 
830 static void
831 xhci_skip_transfer(struct usb_xfer *xfer)
832 {
833 	struct xhci_td *td;
834 	struct xhci_td *td_last;
835 
836 	td = xfer->td_transfer_cache;
837 	td_last = xfer->td_transfer_last;
838 
839 	td = td->alt_next;
840 
841 	usb_pc_cpu_invalidate(td->page_cache);
842 
843 	if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
844 
845 		usb_pc_cpu_invalidate(td_last->page_cache);
846 
847 		/* copy LINK TRB to current waiting location */
848 
849 		td->td_trb[0].qwTrb0 = td_last->td_trb[td_last->ntrb].qwTrb0;
850 		td->td_trb[0].dwTrb2 = td_last->td_trb[td_last->ntrb].dwTrb2;
851 		usb_pc_cpu_flush(td->page_cache);
852 
853 		td->td_trb[0].dwTrb3 = td_last->td_trb[td_last->ntrb].dwTrb3;
854 		usb_pc_cpu_flush(td->page_cache);
855 
856 		xhci_endpoint_doorbell(xfer);
857 	}
858 }
859 
860 /*------------------------------------------------------------------------*
861  *	xhci_check_transfer
862  *------------------------------------------------------------------------*/
863 static void
864 xhci_check_transfer(struct xhci_softc *sc, struct xhci_trb *trb)
865 {
866 	struct xhci_endpoint_ext *pepext;
867 	int64_t offset;
868 	uint64_t td_event;
869 	uint32_t temp;
870 	uint32_t remainder;
871 	uint16_t stream_id;
872 	uint16_t i;
873 	uint8_t status;
874 	uint8_t halted;
875 	uint8_t epno;
876 	uint8_t index;
877 
878 	/* decode TRB */
879 	td_event = le64toh(trb->qwTrb0);
880 	temp = le32toh(trb->dwTrb2);
881 
882 	remainder = XHCI_TRB_2_REM_GET(temp);
883 	status = XHCI_TRB_2_ERROR_GET(temp);
884 	stream_id = XHCI_TRB_2_STREAM_GET(temp);
885 
886 	temp = le32toh(trb->dwTrb3);
887 	epno = XHCI_TRB_3_EP_GET(temp);
888 	index = XHCI_TRB_3_SLOT_GET(temp);
889 
890 	/* check if error means halted */
891 	halted = (status != XHCI_TRB_ERROR_SHORT_PKT &&
892 	    status != XHCI_TRB_ERROR_SUCCESS);
893 
894 	DPRINTF("slot=%u epno=%u stream=%u remainder=%u status=%u\n",
895 	    index, epno, stream_id, remainder, status);
896 
897 	if (index > sc->sc_noslot) {
898 		DPRINTF("Invalid slot.\n");
899 		return;
900 	}
901 
902 	if ((epno == 0) || (epno >= XHCI_MAX_ENDPOINTS)) {
903 		DPRINTF("Invalid endpoint.\n");
904 		return;
905 	}
906 
907 	pepext = &sc->sc_hw.devs[index].endp[epno];
908 
909 	if (pepext->trb_ep_mode != USB_EP_MODE_STREAMS) {
910 		stream_id = 0;
911 		DPRINTF("stream_id=0\n");
912 	} else if (stream_id >= XHCI_MAX_STREAMS) {
913 		DPRINTF("Invalid stream ID.\n");
914 		return;
915 	}
916 
917 	/* try to find the USB transfer that generated the event */
918 	for (i = 0; i != (XHCI_MAX_TRANSFERS - 1); i++) {
919 		struct usb_xfer *xfer;
920 		struct xhci_td *td;
921 
922 		xfer = pepext->xfer[i + (XHCI_MAX_TRANSFERS * stream_id)];
923 		if (xfer == NULL)
924 			continue;
925 
926 		td = xfer->td_transfer_cache;
927 
928 		DPRINTFN(5, "Checking if 0x%016llx == (0x%016llx .. 0x%016llx)\n",
929 			(long long)td_event,
930 			(long long)td->td_self,
931 			(long long)td->td_self + sizeof(td->td_trb));
932 
933 		/*
934 		 * NOTE: Some XHCI implementations might not trigger
935 		 * an event on the last LINK TRB so we need to
936 		 * consider both the last and second last event
937 		 * address as conditions for a successful transfer.
938 		 *
939 		 * NOTE: We assume that the XHCI will only trigger one
940 		 * event per chain of TRBs.
941 		 */
942 
943 		offset = td_event - td->td_self;
944 
945 		if (offset >= 0 &&
946 		    offset < (int64_t)sizeof(td->td_trb)) {
947 
948 			usb_pc_cpu_invalidate(td->page_cache);
949 
950 			/* compute rest of remainder, if any */
951 			for (i = (offset / 16) + 1; i < td->ntrb; i++) {
952 				temp = le32toh(td->td_trb[i].dwTrb2);
953 				remainder += XHCI_TRB_2_BYTES_GET(temp);
954 			}
955 
956 			DPRINTFN(5, "New remainder: %u\n", remainder);
957 
958 			/* clear isochronous transfer errors */
959 			if (xfer->flags_int.isochronous_xfr) {
960 				if (halted) {
961 					halted = 0;
962 					status = XHCI_TRB_ERROR_SUCCESS;
963 					remainder = td->len;
964 				}
965 			}
966 
967 			/* "td->remainder" is verified later */
968 			td->remainder = remainder;
969 			td->status = status;
970 
971 			usb_pc_cpu_flush(td->page_cache);
972 
973 			/*
974 			 * 1) Last transfer descriptor makes the
975 			 * transfer done
976 			 */
977 			if (((void *)td) == xfer->td_transfer_last) {
978 				DPRINTF("TD is last\n");
979 				xhci_generic_done(xfer);
980 				break;
981 			}
982 
983 			/*
984 			 * 2) Any kind of error makes the transfer
985 			 * done
986 			 */
987 			if (halted) {
988 				DPRINTF("TD has I/O error\n");
989 				xhci_generic_done(xfer);
990 				break;
991 			}
992 
993 			/*
994 			 * 3) If there is no alternate next transfer,
995 			 * a short packet also makes the transfer done
996 			 */
997 			if (td->remainder > 0) {
998 				if (td->alt_next == NULL) {
999 					DPRINTF(
1000 					    "short TD has no alternate next\n");
1001 					xhci_generic_done(xfer);
1002 					break;
1003 				}
1004 				DPRINTF("TD has short pkt\n");
1005 				if (xfer->flags_int.short_frames_ok ||
1006 				    xfer->flags_int.isochronous_xfr ||
1007 				    xfer->flags_int.control_xfr) {
1008 					/* follow the alt next */
1009 					xfer->td_transfer_cache = td->alt_next;
1010 					xhci_activate_transfer(xfer);
1011 					break;
1012 				}
1013 				xhci_skip_transfer(xfer);
1014 				xhci_generic_done(xfer);
1015 				break;
1016 			}
1017 
1018 			/*
1019 			 * 4) Transfer complete - go to next TD
1020 			 */
1021 			DPRINTF("Following next TD\n");
1022 			xfer->td_transfer_cache = td->obj_next;
1023 			xhci_activate_transfer(xfer);
1024 			break;		/* there should only be one match */
1025 		}
1026 	}
1027 }
1028 
1029 static int
1030 xhci_check_command(struct xhci_softc *sc, struct xhci_trb *trb)
1031 {
1032 	if (sc->sc_cmd_addr == trb->qwTrb0) {
1033 		DPRINTF("Received command event\n");
1034 		sc->sc_cmd_result[0] = trb->dwTrb2;
1035 		sc->sc_cmd_result[1] = trb->dwTrb3;
1036 		cv_signal(&sc->sc_cmd_cv);
1037 		return (1);	/* command match */
1038 	}
1039 	return (0);
1040 }
1041 
1042 static int
1043 xhci_interrupt_poll(struct xhci_softc *sc)
1044 {
1045 	struct usb_page_search buf_res;
1046 	struct xhci_hw_root *phwr;
1047 	uint64_t addr;
1048 	uint32_t temp;
1049 	int retval = 0;
1050 	uint16_t i;
1051 	uint8_t event;
1052 	uint8_t j;
1053 	uint8_t k;
1054 	uint8_t t;
1055 
1056 	usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
1057 
1058 	phwr = buf_res.buffer;
1059 
1060 	/* Receive any events */
1061 
1062 	usb_pc_cpu_invalidate(&sc->sc_hw.root_pc);
1063 
1064 	i = sc->sc_event_idx;
1065 	j = sc->sc_event_ccs;
1066 	t = 2;
1067 
1068 	while (1) {
1069 
1070 		temp = le32toh(phwr->hwr_events[i].dwTrb3);
1071 
1072 		k = (temp & XHCI_TRB_3_CYCLE_BIT) ? 1 : 0;
1073 
1074 		if (j != k)
1075 			break;
1076 
1077 		event = XHCI_TRB_3_TYPE_GET(temp);
1078 
1079 		DPRINTFN(10, "event[%u] = %u (0x%016llx 0x%08lx 0x%08lx)\n",
1080 		    i, event, (long long)le64toh(phwr->hwr_events[i].qwTrb0),
1081 		    (long)le32toh(phwr->hwr_events[i].dwTrb2),
1082 		    (long)le32toh(phwr->hwr_events[i].dwTrb3));
1083 
1084 		switch (event) {
1085 		case XHCI_TRB_EVENT_TRANSFER:
1086 			xhci_check_transfer(sc, &phwr->hwr_events[i]);
1087 			break;
1088 		case XHCI_TRB_EVENT_CMD_COMPLETE:
1089 			retval |= xhci_check_command(sc, &phwr->hwr_events[i]);
1090 			break;
1091 		default:
1092 			DPRINTF("Unhandled event = %u\n", event);
1093 			break;
1094 		}
1095 
1096 		i++;
1097 
1098 		if (i == XHCI_MAX_EVENTS) {
1099 			i = 0;
1100 			j ^= 1;
1101 
1102 			/* check for timeout */
1103 			if (!--t)
1104 				break;
1105 		}
1106 	}
1107 
1108 	sc->sc_event_idx = i;
1109 	sc->sc_event_ccs = j;
1110 
1111 	/*
1112 	 * NOTE: The Event Ring Dequeue Pointer Register is 64-bit
1113 	 * latched. That means to activate the register we need to
1114 	 * write both the low and high double word of the 64-bit
1115 	 * register.
1116 	 */
1117 
1118 	addr = buf_res.physaddr;
1119 	addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_events[i];
1120 
1121 	/* try to clear busy bit */
1122 	addr |= XHCI_ERDP_LO_BUSY;
1123 
1124 	XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
1125 	XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
1126 
1127 	return (retval);
1128 }
1129 
1130 static usb_error_t
1131 xhci_do_command(struct xhci_softc *sc, struct xhci_trb *trb,
1132     uint16_t timeout_ms)
1133 {
1134 	struct usb_page_search buf_res;
1135 	struct xhci_hw_root *phwr;
1136 	uint64_t addr;
1137 	uint32_t temp;
1138 	uint8_t i;
1139 	uint8_t j;
1140 	uint8_t timeout = 0;
1141 	int err;
1142 
1143 	XHCI_CMD_ASSERT_LOCKED(sc);
1144 
1145 	/* get hardware root structure */
1146 
1147 	usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
1148 
1149 	phwr = buf_res.buffer;
1150 
1151 	/* Queue command */
1152 
1153 	USB_BUS_LOCK(&sc->sc_bus);
1154 retry:
1155 	i = sc->sc_command_idx;
1156 	j = sc->sc_command_ccs;
1157 
1158 	DPRINTFN(10, "command[%u] = %u (0x%016llx, 0x%08lx, 0x%08lx)\n",
1159 	    i, XHCI_TRB_3_TYPE_GET(le32toh(trb->dwTrb3)),
1160 	    (long long)le64toh(trb->qwTrb0),
1161 	    (long)le32toh(trb->dwTrb2),
1162 	    (long)le32toh(trb->dwTrb3));
1163 
1164 	phwr->hwr_commands[i].qwTrb0 = trb->qwTrb0;
1165 	phwr->hwr_commands[i].dwTrb2 = trb->dwTrb2;
1166 
1167 	usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1168 
1169 	temp = trb->dwTrb3;
1170 
1171 	if (j)
1172 		temp |= htole32(XHCI_TRB_3_CYCLE_BIT);
1173 	else
1174 		temp &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
1175 
1176 	temp &= ~htole32(XHCI_TRB_3_TC_BIT);
1177 
1178 	phwr->hwr_commands[i].dwTrb3 = temp;
1179 
1180 	usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1181 
1182 	addr = buf_res.physaddr;
1183 	addr += (uintptr_t)&((struct xhci_hw_root *)0)->hwr_commands[i];
1184 
1185 	sc->sc_cmd_addr = htole64(addr);
1186 
1187 	i++;
1188 
1189 	if (i == (XHCI_MAX_COMMANDS - 1)) {
1190 
1191 		if (j) {
1192 			temp = htole32(XHCI_TRB_3_TC_BIT |
1193 			    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
1194 			    XHCI_TRB_3_CYCLE_BIT);
1195 		} else {
1196 			temp = htole32(XHCI_TRB_3_TC_BIT |
1197 			    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
1198 		}
1199 
1200 		phwr->hwr_commands[i].dwTrb3 = temp;
1201 
1202 		usb_pc_cpu_flush(&sc->sc_hw.root_pc);
1203 
1204 		i = 0;
1205 		j ^= 1;
1206 	}
1207 
1208 	sc->sc_command_idx = i;
1209 	sc->sc_command_ccs = j;
1210 
1211 	XWRITE4(sc, door, XHCI_DOORBELL(0), 0);
1212 
1213 	err = cv_timedwait(&sc->sc_cmd_cv, &sc->sc_bus.bus_mtx,
1214 	    USB_MS_TO_TICKS(timeout_ms));
1215 
1216 	/*
1217 	 * In some error cases event interrupts are not generated.
1218 	 * Poll one time to see if the command has completed.
1219 	 */
1220 	if (err != 0 && xhci_interrupt_poll(sc) != 0) {
1221 		DPRINTF("Command was completed when polling\n");
1222 		err = 0;
1223 	}
1224 	if (err != 0) {
1225 		DPRINTF("Command timeout!\n");
1226 		/*
1227 		 * After some weeks of continuous operation, it has
1228 		 * been observed that the ASMedia Technology, ASM1042
1229 		 * SuperSpeed USB Host Controller can suddenly stop
1230 		 * accepting commands via the command queue. Try to
1231 		 * first reset the command queue. If that fails do a
1232 		 * host controller reset.
1233 		 */
1234 		if (timeout == 0 &&
1235 		    xhci_reset_command_queue_locked(sc) == 0) {
1236 			temp = le32toh(trb->dwTrb3);
1237 
1238 			/*
1239 			 * Avoid infinite XHCI reset loops if the set
1240 			 * address command fails to respond due to a
1241 			 * non-enumerating device:
1242 			 */
1243 			if (XHCI_TRB_3_TYPE_GET(temp) == XHCI_TRB_TYPE_ADDRESS_DEVICE &&
1244 			    (temp & XHCI_TRB_3_BSR_BIT) == 0) {
1245 				DPRINTF("Set address timeout\n");
1246 			} else {
1247 				timeout = 1;
1248 				goto retry;
1249 			}
1250 		} else {
1251 			DPRINTF("Controller reset!\n");
1252 			usb_bus_reset_async_locked(&sc->sc_bus);
1253 		}
1254 		err = USB_ERR_TIMEOUT;
1255 		trb->dwTrb2 = 0;
1256 		trb->dwTrb3 = 0;
1257 	} else {
1258 		temp = le32toh(sc->sc_cmd_result[0]);
1259 		if (XHCI_TRB_2_ERROR_GET(temp) != XHCI_TRB_ERROR_SUCCESS)
1260 			err = USB_ERR_IOERROR;
1261 
1262 		trb->dwTrb2 = sc->sc_cmd_result[0];
1263 		trb->dwTrb3 = sc->sc_cmd_result[1];
1264 	}
1265 
1266 	USB_BUS_UNLOCK(&sc->sc_bus);
1267 
1268 	return (err);
1269 }
1270 
1271 #if 0
1272 static usb_error_t
1273 xhci_cmd_nop(struct xhci_softc *sc)
1274 {
1275 	struct xhci_trb trb;
1276 	uint32_t temp;
1277 
1278 	DPRINTF("\n");
1279 
1280 	trb.qwTrb0 = 0;
1281 	trb.dwTrb2 = 0;
1282 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NOOP);
1283 
1284 	trb.dwTrb3 = htole32(temp);
1285 
1286 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1287 }
1288 #endif
1289 
1290 static usb_error_t
1291 xhci_cmd_enable_slot(struct xhci_softc *sc, uint8_t *pslot)
1292 {
1293 	struct xhci_trb trb;
1294 	uint32_t temp;
1295 	usb_error_t err;
1296 
1297 	DPRINTF("\n");
1298 
1299 	trb.qwTrb0 = 0;
1300 	trb.dwTrb2 = 0;
1301 	trb.dwTrb3 = htole32(XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT));
1302 
1303 	err = xhci_do_command(sc, &trb, 100 /* ms */);
1304 	if (err)
1305 		goto done;
1306 
1307 	temp = le32toh(trb.dwTrb3);
1308 
1309 	*pslot = XHCI_TRB_3_SLOT_GET(temp);
1310 
1311 done:
1312 	return (err);
1313 }
1314 
1315 static usb_error_t
1316 xhci_cmd_disable_slot(struct xhci_softc *sc, uint8_t slot_id)
1317 {
1318 	struct xhci_trb trb;
1319 	uint32_t temp;
1320 
1321 	DPRINTF("\n");
1322 
1323 	trb.qwTrb0 = 0;
1324 	trb.dwTrb2 = 0;
1325 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT) |
1326 	    XHCI_TRB_3_SLOT_SET(slot_id);
1327 
1328 	trb.dwTrb3 = htole32(temp);
1329 
1330 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1331 }
1332 
1333 static usb_error_t
1334 xhci_cmd_set_address(struct xhci_softc *sc, uint64_t input_ctx,
1335     uint8_t bsr, uint8_t slot_id)
1336 {
1337 	struct xhci_trb trb;
1338 	uint32_t temp;
1339 
1340 	DPRINTF("\n");
1341 
1342 	trb.qwTrb0 = htole64(input_ctx);
1343 	trb.dwTrb2 = 0;
1344 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
1345 	    XHCI_TRB_3_SLOT_SET(slot_id);
1346 
1347 	if (bsr)
1348 		temp |= XHCI_TRB_3_BSR_BIT;
1349 
1350 	trb.dwTrb3 = htole32(temp);
1351 
1352 	return (xhci_do_command(sc, &trb, 500 /* ms */));
1353 }
1354 
1355 static usb_error_t
1356 xhci_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t address)
1357 {
1358 	struct usb_page_search buf_inp;
1359 	struct usb_page_search buf_dev;
1360 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
1361 	struct xhci_hw_dev *hdev;
1362 	struct xhci_dev_ctx *pdev;
1363 	struct xhci_endpoint_ext *pepext;
1364 	uint32_t temp;
1365 	uint16_t mps;
1366 	usb_error_t err;
1367 	uint8_t index;
1368 
1369 	/* the root HUB case is not handled here */
1370 	if (udev->parent_hub == NULL)
1371 		return (USB_ERR_INVAL);
1372 
1373 	index = udev->controller_slot_id;
1374 
1375 	hdev = 	&sc->sc_hw.devs[index];
1376 
1377 	if (mtx != NULL)
1378 		mtx_unlock(mtx);
1379 
1380 	XHCI_CMD_LOCK(sc);
1381 
1382 	switch (hdev->state) {
1383 	case XHCI_ST_DEFAULT:
1384 	case XHCI_ST_ENABLED:
1385 
1386 		hdev->state = XHCI_ST_ENABLED;
1387 
1388 		/* set configure mask to slot and EP0 */
1389 		xhci_configure_mask(udev, 3, 0);
1390 
1391 		/* configure input slot context structure */
1392 		err = xhci_configure_device(udev);
1393 
1394 		if (err != 0) {
1395 			DPRINTF("Could not configure device\n");
1396 			break;
1397 		}
1398 
1399 		/* configure input endpoint context structure */
1400 		switch (udev->speed) {
1401 		case USB_SPEED_LOW:
1402 		case USB_SPEED_FULL:
1403 			mps = 8;
1404 			break;
1405 		case USB_SPEED_HIGH:
1406 			mps = 64;
1407 			break;
1408 		default:
1409 			mps = 512;
1410 			break;
1411 		}
1412 
1413 		pepext = xhci_get_endpoint_ext(udev,
1414 		    &udev->ctrl_ep_desc);
1415 
1416 		/* ensure the control endpoint is setup again */
1417 		USB_BUS_LOCK(udev->bus);
1418 		pepext->trb_halted = 1;
1419 		pepext->trb_running = 0;
1420 		USB_BUS_UNLOCK(udev->bus);
1421 
1422 		err = xhci_configure_endpoint(udev,
1423 		    &udev->ctrl_ep_desc, pepext,
1424 		    0, 1, 1, 0, mps, mps, USB_EP_MODE_DEFAULT);
1425 
1426 		if (err != 0) {
1427 			DPRINTF("Could not configure default endpoint\n");
1428 			break;
1429 		}
1430 
1431 		/* execute set address command */
1432 		usbd_get_page(&hdev->input_pc, 0, &buf_inp);
1433 
1434 		err = xhci_cmd_set_address(sc, buf_inp.physaddr,
1435 		    (address == 0), index);
1436 
1437 		if (err != 0) {
1438 			temp = le32toh(sc->sc_cmd_result[0]);
1439 			if (address == 0 && sc->sc_port_route != NULL &&
1440 			    XHCI_TRB_2_ERROR_GET(temp) ==
1441 			    XHCI_TRB_ERROR_PARAMETER) {
1442 				/* LynxPoint XHCI - ports are not switchable */
1443 				/* Un-route all ports from the XHCI */
1444 				sc->sc_port_route(sc->sc_bus.parent, 0, ~0);
1445 			}
1446 			DPRINTF("Could not set address "
1447 			    "for slot %u.\n", index);
1448 			if (address != 0)
1449 				break;
1450 		}
1451 
1452 		/* update device address to new value */
1453 
1454 		usbd_get_page(&hdev->device_pc, 0, &buf_dev);
1455 		pdev = buf_dev.buffer;
1456 		usb_pc_cpu_invalidate(&hdev->device_pc);
1457 
1458 		temp = xhci_ctx_get_le32(sc, &pdev->ctx_slot.dwSctx3);
1459 		udev->address = XHCI_SCTX_3_DEV_ADDR_GET(temp);
1460 
1461 		/* update device state to new value */
1462 
1463 		if (address != 0)
1464 			hdev->state = XHCI_ST_ADDRESSED;
1465 		else
1466 			hdev->state = XHCI_ST_DEFAULT;
1467 		break;
1468 
1469 	default:
1470 		DPRINTF("Wrong state for set address.\n");
1471 		err = USB_ERR_IOERROR;
1472 		break;
1473 	}
1474 	XHCI_CMD_UNLOCK(sc);
1475 
1476 	if (mtx != NULL)
1477 		mtx_lock(mtx);
1478 
1479 	return (err);
1480 }
1481 
1482 static usb_error_t
1483 xhci_cmd_configure_ep(struct xhci_softc *sc, uint64_t input_ctx,
1484     uint8_t deconfigure, uint8_t slot_id)
1485 {
1486 	struct xhci_trb trb;
1487 	uint32_t temp;
1488 
1489 	DPRINTF("\n");
1490 
1491 	trb.qwTrb0 = htole64(input_ctx);
1492 	trb.dwTrb2 = 0;
1493 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP) |
1494 	    XHCI_TRB_3_SLOT_SET(slot_id);
1495 
1496 	if (deconfigure)
1497 		temp |= XHCI_TRB_3_DCEP_BIT;
1498 
1499 	trb.dwTrb3 = htole32(temp);
1500 
1501 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1502 }
1503 
1504 static usb_error_t
1505 xhci_cmd_evaluate_ctx(struct xhci_softc *sc, uint64_t input_ctx,
1506     uint8_t slot_id)
1507 {
1508 	struct xhci_trb trb;
1509 	uint32_t temp;
1510 
1511 	DPRINTF("\n");
1512 
1513 	trb.qwTrb0 = htole64(input_ctx);
1514 	trb.dwTrb2 = 0;
1515 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX) |
1516 	    XHCI_TRB_3_SLOT_SET(slot_id);
1517 	trb.dwTrb3 = htole32(temp);
1518 
1519 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1520 }
1521 
1522 static usb_error_t
1523 xhci_cmd_reset_ep(struct xhci_softc *sc, uint8_t preserve,
1524     uint8_t ep_id, uint8_t slot_id)
1525 {
1526 	struct xhci_trb trb;
1527 	uint32_t temp;
1528 
1529 	DPRINTF("\n");
1530 
1531 	trb.qwTrb0 = 0;
1532 	trb.dwTrb2 = 0;
1533 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP) |
1534 	    XHCI_TRB_3_SLOT_SET(slot_id) |
1535 	    XHCI_TRB_3_EP_SET(ep_id);
1536 
1537 	if (preserve)
1538 		temp |= XHCI_TRB_3_PRSV_BIT;
1539 
1540 	trb.dwTrb3 = htole32(temp);
1541 
1542 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1543 }
1544 
1545 static usb_error_t
1546 xhci_cmd_set_tr_dequeue_ptr(struct xhci_softc *sc, uint64_t dequeue_ptr,
1547     uint16_t stream_id, uint8_t ep_id, uint8_t slot_id)
1548 {
1549 	struct xhci_trb trb;
1550 	uint32_t temp;
1551 
1552 	DPRINTF("\n");
1553 
1554 	trb.qwTrb0 = htole64(dequeue_ptr);
1555 
1556 	temp = XHCI_TRB_2_STREAM_SET(stream_id);
1557 	trb.dwTrb2 = htole32(temp);
1558 
1559 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE) |
1560 	    XHCI_TRB_3_SLOT_SET(slot_id) |
1561 	    XHCI_TRB_3_EP_SET(ep_id);
1562 	trb.dwTrb3 = htole32(temp);
1563 
1564 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1565 }
1566 
1567 static usb_error_t
1568 xhci_cmd_stop_ep(struct xhci_softc *sc, uint8_t suspend,
1569     uint8_t ep_id, uint8_t slot_id)
1570 {
1571 	struct xhci_trb trb;
1572 	uint32_t temp;
1573 
1574 	DPRINTF("\n");
1575 
1576 	trb.qwTrb0 = 0;
1577 	trb.dwTrb2 = 0;
1578 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP) |
1579 	    XHCI_TRB_3_SLOT_SET(slot_id) |
1580 	    XHCI_TRB_3_EP_SET(ep_id);
1581 
1582 	if (suspend)
1583 		temp |= XHCI_TRB_3_SUSP_EP_BIT;
1584 
1585 	trb.dwTrb3 = htole32(temp);
1586 
1587 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1588 }
1589 
1590 static usb_error_t
1591 xhci_cmd_reset_dev(struct xhci_softc *sc, uint8_t slot_id)
1592 {
1593 	struct xhci_trb trb;
1594 	uint32_t temp;
1595 
1596 	DPRINTF("\n");
1597 
1598 	trb.qwTrb0 = 0;
1599 	trb.dwTrb2 = 0;
1600 	temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_DEVICE) |
1601 	    XHCI_TRB_3_SLOT_SET(slot_id);
1602 
1603 	trb.dwTrb3 = htole32(temp);
1604 
1605 	return (xhci_do_command(sc, &trb, 100 /* ms */));
1606 }
1607 
1608 /*------------------------------------------------------------------------*
1609  *	xhci_interrupt - XHCI interrupt handler
1610  *------------------------------------------------------------------------*/
1611 void
1612 xhci_interrupt(struct xhci_softc *sc)
1613 {
1614 	uint32_t status;
1615 	uint32_t temp;
1616 
1617 	USB_BUS_LOCK(&sc->sc_bus);
1618 
1619 	status = XREAD4(sc, oper, XHCI_USBSTS);
1620 
1621 	/* acknowledge interrupts, if any */
1622 	if (status != 0) {
1623 		XWRITE4(sc, oper, XHCI_USBSTS, status);
1624 		DPRINTFN(16, "real interrupt (status=0x%08x)\n", status);
1625 	}
1626 
1627 	temp = XREAD4(sc, runt, XHCI_IMAN(0));
1628 
1629 	/* force clearing of pending interrupts */
1630 	if (temp & XHCI_IMAN_INTR_PEND)
1631 		XWRITE4(sc, runt, XHCI_IMAN(0), temp);
1632 
1633 	/* check for event(s) */
1634 	xhci_interrupt_poll(sc);
1635 
1636 	if (status & (XHCI_STS_PCD | XHCI_STS_HCH |
1637 	    XHCI_STS_HSE | XHCI_STS_HCE)) {
1638 
1639 		if (status & XHCI_STS_PCD) {
1640 			xhci_root_intr(sc);
1641 		}
1642 
1643 		if (status & XHCI_STS_HCH) {
1644 			printf("%s: host controller halted\n",
1645 			    __FUNCTION__);
1646 		}
1647 
1648 		if (status & XHCI_STS_HSE) {
1649 			printf("%s: host system error\n",
1650 			    __FUNCTION__);
1651 		}
1652 
1653 		if (status & XHCI_STS_HCE) {
1654 			printf("%s: host controller error\n",
1655 			   __FUNCTION__);
1656 		}
1657 	}
1658 	USB_BUS_UNLOCK(&sc->sc_bus);
1659 }
1660 
1661 /*------------------------------------------------------------------------*
1662  *	xhci_timeout - XHCI timeout handler
1663  *------------------------------------------------------------------------*/
1664 static void
1665 xhci_timeout(void *arg)
1666 {
1667 	struct usb_xfer *xfer = arg;
1668 
1669 	DPRINTF("xfer=%p\n", xfer);
1670 
1671 	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1672 
1673 	/* transfer is transferred */
1674 	xhci_device_done(xfer, USB_ERR_TIMEOUT);
1675 }
1676 
1677 static void
1678 xhci_do_poll(struct usb_bus *bus)
1679 {
1680 	struct xhci_softc *sc = XHCI_BUS2SC(bus);
1681 
1682 	USB_BUS_LOCK(&sc->sc_bus);
1683 	xhci_interrupt_poll(sc);
1684 	USB_BUS_UNLOCK(&sc->sc_bus);
1685 }
1686 
1687 static void
1688 xhci_setup_generic_chain_sub(struct xhci_std_temp *temp)
1689 {
1690 	struct usb_page_search buf_res;
1691 	struct xhci_td *td;
1692 	struct xhci_td *td_next;
1693 	struct xhci_td *td_alt_next;
1694 	struct xhci_td *td_first;
1695 	uint32_t buf_offset;
1696 	uint32_t average;
1697 	uint32_t len_old;
1698 	uint32_t npkt_off;
1699 	uint32_t dword;
1700 	uint8_t shortpkt_old;
1701 	uint8_t precompute;
1702 	uint8_t x;
1703 
1704 	td_alt_next = NULL;
1705 	buf_offset = 0;
1706 	shortpkt_old = temp->shortpkt;
1707 	len_old = temp->len;
1708 	npkt_off = 0;
1709 	precompute = 1;
1710 
1711 restart:
1712 
1713 	td = temp->td;
1714 	td_next = td_first = temp->td_next;
1715 
1716 	while (1) {
1717 
1718 		if (temp->len == 0) {
1719 
1720 			if (temp->shortpkt)
1721 				break;
1722 
1723 			/* send a Zero Length Packet, ZLP, last */
1724 
1725 			temp->shortpkt = 1;
1726 			average = 0;
1727 
1728 		} else {
1729 
1730 			average = temp->average;
1731 
1732 			if (temp->len < average) {
1733 				if (temp->len % temp->max_packet_size) {
1734 					temp->shortpkt = 1;
1735 				}
1736 				average = temp->len;
1737 			}
1738 		}
1739 
1740 		if (td_next == NULL)
1741 			panic("%s: out of XHCI transfer descriptors!", __FUNCTION__);
1742 
1743 		/* get next TD */
1744 
1745 		td = td_next;
1746 		td_next = td->obj_next;
1747 
1748 		/* check if we are pre-computing */
1749 
1750 		if (precompute) {
1751 
1752 			/* update remaining length */
1753 
1754 			temp->len -= average;
1755 
1756 			continue;
1757 		}
1758 		/* fill out current TD */
1759 
1760 		td->len = average;
1761 		td->remainder = 0;
1762 		td->status = 0;
1763 
1764 		/* update remaining length */
1765 
1766 		temp->len -= average;
1767 
1768 		/* reset TRB index */
1769 
1770 		x = 0;
1771 
1772 		if (temp->trb_type == XHCI_TRB_TYPE_SETUP_STAGE) {
1773 			/* immediate data */
1774 
1775 			if (average > 8)
1776 				average = 8;
1777 
1778 			td->td_trb[0].qwTrb0 = 0;
1779 
1780 			usbd_copy_out(temp->pc, temp->offset + buf_offset,
1781 			   (uint8_t *)(uintptr_t)&td->td_trb[0].qwTrb0,
1782 			   average);
1783 
1784 			dword = XHCI_TRB_2_BYTES_SET(8) |
1785 			    XHCI_TRB_2_TDSZ_SET(0) |
1786 			    XHCI_TRB_2_IRQ_SET(0);
1787 
1788 			td->td_trb[0].dwTrb2 = htole32(dword);
1789 
1790 			dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
1791 			  XHCI_TRB_3_IDT_BIT | XHCI_TRB_3_CYCLE_BIT;
1792 
1793 			/* check wLength */
1794 			if (td->td_trb[0].qwTrb0 &
1795 			   htole64(XHCI_TRB_0_WLENGTH_MASK)) {
1796 				if (td->td_trb[0].qwTrb0 &
1797 				    htole64(XHCI_TRB_0_DIR_IN_MASK))
1798 					dword |= XHCI_TRB_3_TRT_IN;
1799 				else
1800 					dword |= XHCI_TRB_3_TRT_OUT;
1801 			}
1802 
1803 			td->td_trb[0].dwTrb3 = htole32(dword);
1804 #ifdef USB_DEBUG
1805 			xhci_dump_trb(&td->td_trb[x]);
1806 #endif
1807 			x++;
1808 
1809 		} else do {
1810 
1811 			uint32_t npkt;
1812 
1813 			/* fill out buffer pointers */
1814 
1815 			if (average == 0) {
1816 				memset(&buf_res, 0, sizeof(buf_res));
1817 			} else {
1818 				usbd_get_page(temp->pc, temp->offset +
1819 				    buf_offset, &buf_res);
1820 
1821 				/* get length to end of page */
1822 				if (buf_res.length > average)
1823 					buf_res.length = average;
1824 
1825 				/* check for maximum length */
1826 				if (buf_res.length > XHCI_TD_PAGE_SIZE)
1827 					buf_res.length = XHCI_TD_PAGE_SIZE;
1828 
1829 				npkt_off += buf_res.length;
1830 			}
1831 
1832 			/* set up npkt */
1833 			npkt = howmany(len_old - npkt_off,
1834 				       temp->max_packet_size);
1835 
1836 			if (npkt == 0)
1837 				npkt = 1;
1838 			else if (npkt > 31)
1839 				npkt = 31;
1840 
1841 			/* fill out TRB's */
1842 			td->td_trb[x].qwTrb0 =
1843 			    htole64((uint64_t)buf_res.physaddr);
1844 
1845 			dword =
1846 			  XHCI_TRB_2_BYTES_SET(buf_res.length) |
1847 			  XHCI_TRB_2_TDSZ_SET(npkt) |
1848 			  XHCI_TRB_2_IRQ_SET(0);
1849 
1850 			td->td_trb[x].dwTrb2 = htole32(dword);
1851 
1852 			switch (temp->trb_type) {
1853 			case XHCI_TRB_TYPE_ISOCH:
1854 				dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1855 				    XHCI_TRB_3_TBC_SET(temp->tbc) |
1856 				    XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
1857 				if (td != td_first) {
1858 					dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
1859 				} else if (temp->do_isoc_sync != 0) {
1860 					temp->do_isoc_sync = 0;
1861 					/* wait until "isoc_frame" */
1862 					dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1863 					    XHCI_TRB_3_FRID_SET(temp->isoc_frame / 8);
1864 				} else {
1865 					/* start data transfer at next interval */
1866 					dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
1867 					    XHCI_TRB_3_ISO_SIA_BIT;
1868 				}
1869 				if (temp->direction == UE_DIR_IN)
1870 					dword |= XHCI_TRB_3_ISP_BIT;
1871 				break;
1872 			case XHCI_TRB_TYPE_DATA_STAGE:
1873 				dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1874 				    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE);
1875 				if (temp->direction == UE_DIR_IN)
1876 					dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
1877 				/*
1878 				 * Section 3.2.9 in the XHCI
1879 				 * specification about control
1880 				 * transfers says that we should use a
1881 				 * normal-TRB if there are more TRBs
1882 				 * extending the data-stage
1883 				 * TRB. Update the "trb_type".
1884 				 */
1885 				temp->trb_type = XHCI_TRB_TYPE_NORMAL;
1886 				break;
1887 			case XHCI_TRB_TYPE_STATUS_STAGE:
1888 				dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1889 				    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE);
1890 				if (temp->direction == UE_DIR_IN)
1891 					dword |= XHCI_TRB_3_DIR_IN;
1892 				break;
1893 			default:	/* XHCI_TRB_TYPE_NORMAL */
1894 				dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
1895 				    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
1896 				if (temp->direction == UE_DIR_IN)
1897 					dword |= XHCI_TRB_3_ISP_BIT;
1898 				break;
1899 			}
1900 			td->td_trb[x].dwTrb3 = htole32(dword);
1901 
1902 			average -= buf_res.length;
1903 			buf_offset += buf_res.length;
1904 #ifdef USB_DEBUG
1905 			xhci_dump_trb(&td->td_trb[x]);
1906 #endif
1907 			x++;
1908 
1909 		} while (average != 0);
1910 
1911 		td->td_trb[x-1].dwTrb3 |= htole32(XHCI_TRB_3_IOC_BIT);
1912 
1913 		/* store number of data TRB's */
1914 
1915 		td->ntrb = x;
1916 
1917 		DPRINTF("NTRB=%u\n", x);
1918 
1919 		/* fill out link TRB */
1920 
1921 		if (td_next != NULL) {
1922 			/* link the current TD with the next one */
1923 			td->td_trb[x].qwTrb0 = htole64((uint64_t)td_next->td_self);
1924 			DPRINTF("LINK=0x%08llx\n", (long long)td_next->td_self);
1925 		} else {
1926 			/* this field will get updated later */
1927 			DPRINTF("NOLINK\n");
1928 		}
1929 
1930 		dword = XHCI_TRB_2_IRQ_SET(0);
1931 
1932 		td->td_trb[x].dwTrb2 = htole32(dword);
1933 
1934 		dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
1935 		    XHCI_TRB_3_CYCLE_BIT | XHCI_TRB_3_IOC_BIT |
1936 		    /*
1937 		     * CHAIN-BIT: Ensure that a multi-TRB IN-endpoint
1938 		     * frame only receives a single short packet event
1939 		     * by setting the CHAIN bit in the LINK field. In
1940 		     * addition some XHCI controllers have problems
1941 		     * sending a ZLP unless the CHAIN-BIT is set in
1942 		     * the LINK TRB.
1943 		     */
1944 		    XHCI_TRB_3_CHAIN_BIT;
1945 
1946 		td->td_trb[x].dwTrb3 = htole32(dword);
1947 
1948 		td->alt_next = td_alt_next;
1949 #ifdef USB_DEBUG
1950 		xhci_dump_trb(&td->td_trb[x]);
1951 #endif
1952 		usb_pc_cpu_flush(td->page_cache);
1953 	}
1954 
1955 	if (precompute) {
1956 		precompute = 0;
1957 
1958 		/* set up alt next pointer, if any */
1959 		if (temp->last_frame) {
1960 			td_alt_next = NULL;
1961 		} else {
1962 			/* we use this field internally */
1963 			td_alt_next = td_next;
1964 		}
1965 
1966 		/* restore */
1967 		temp->shortpkt = shortpkt_old;
1968 		temp->len = len_old;
1969 		goto restart;
1970 	}
1971 
1972 	/*
1973 	 * Remove cycle bit from the first TRB if we are
1974 	 * stepping them:
1975 	 */
1976 	if (temp->step_td != 0) {
1977 		td_first->td_trb[0].dwTrb3 &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
1978 		usb_pc_cpu_flush(td_first->page_cache);
1979 	}
1980 
1981 	/* clear TD SIZE to zero, hence this is the last TRB */
1982 	/* remove chain bit because this is the last data TRB in the chain */
1983 	td->td_trb[td->ntrb - 1].dwTrb2 &= ~htole32(XHCI_TRB_2_TDSZ_SET(15));
1984 	td->td_trb[td->ntrb - 1].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
1985 	/* remove CHAIN-BIT from last LINK TRB */
1986 	td->td_trb[td->ntrb].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
1987 
1988 	usb_pc_cpu_flush(td->page_cache);
1989 
1990 	temp->td = td;
1991 	temp->td_next = td_next;
1992 }
1993 
1994 static void
1995 xhci_setup_generic_chain(struct usb_xfer *xfer)
1996 {
1997 	struct xhci_std_temp temp;
1998 	struct xhci_td *td;
1999 	uint32_t x;
2000 	uint32_t y;
2001 	uint8_t mult;
2002 
2003 	temp.do_isoc_sync = 0;
2004 	temp.step_td = 0;
2005 	temp.tbc = 0;
2006 	temp.tlbpc = 0;
2007 	temp.average = xfer->max_hc_frame_size;
2008 	temp.max_packet_size = xfer->max_packet_size;
2009 	temp.sc = XHCI_BUS2SC(xfer->xroot->bus);
2010 	temp.pc = NULL;
2011 	temp.last_frame = 0;
2012 	temp.offset = 0;
2013 	temp.multishort = xfer->flags_int.isochronous_xfr ||
2014 	    xfer->flags_int.control_xfr ||
2015 	    xfer->flags_int.short_frames_ok;
2016 
2017 	/* toggle the DMA set we are using */
2018 	xfer->flags_int.curr_dma_set ^= 1;
2019 
2020 	/* get next DMA set */
2021 	td = xfer->td_start[xfer->flags_int.curr_dma_set];
2022 
2023 	temp.td = NULL;
2024 	temp.td_next = td;
2025 
2026 	xfer->td_transfer_first = td;
2027 	xfer->td_transfer_cache = td;
2028 
2029 	if (xfer->flags_int.isochronous_xfr) {
2030 		uint8_t shift;
2031 
2032 		/* compute multiplier for ISOCHRONOUS transfers */
2033 		mult = xfer->endpoint->ecomp ?
2034 		    UE_GET_SS_ISO_MULT(xfer->endpoint->ecomp->bmAttributes)
2035 		    : 0;
2036 		/* check for USB 2.0 multiplier */
2037 		if (mult == 0) {
2038 			mult = (xfer->endpoint->edesc->
2039 			    wMaxPacketSize[1] >> 3) & 3;
2040 		}
2041 		/* range check */
2042 		if (mult > 2)
2043 			mult = 3;
2044 		else
2045 			mult++;
2046 
2047 		x = XREAD4(temp.sc, runt, XHCI_MFINDEX);
2048 
2049 		DPRINTF("MFINDEX=0x%08x\n", x);
2050 
2051 		switch (usbd_get_speed(xfer->xroot->udev)) {
2052 		case USB_SPEED_FULL:
2053 			shift = 3;
2054 			temp.isoc_delta = 8;	/* 1ms */
2055 			x += temp.isoc_delta - 1;
2056 			x &= ~(temp.isoc_delta - 1);
2057 			break;
2058 		default:
2059 			shift = usbd_xfer_get_fps_shift(xfer);
2060 			temp.isoc_delta = 1U << shift;
2061 			x += temp.isoc_delta - 1;
2062 			x &= ~(temp.isoc_delta - 1);
2063 			/* simple frame load balancing */
2064 			x += xfer->endpoint->usb_uframe;
2065 			break;
2066 		}
2067 
2068 		y = XHCI_MFINDEX_GET(x - xfer->endpoint->isoc_next);
2069 
2070 		if ((xfer->endpoint->is_synced == 0) ||
2071 		    (y < (xfer->nframes << shift)) ||
2072 		    (XHCI_MFINDEX_GET(-y) >= (128 * 8))) {
2073 			/*
2074 			 * If there is data underflow or the pipe
2075 			 * queue is empty we schedule the transfer a
2076 			 * few frames ahead of the current frame
2077 			 * position. Else two isochronous transfers
2078 			 * might overlap.
2079 			 */
2080 			xfer->endpoint->isoc_next = XHCI_MFINDEX_GET(x + (3 * 8));
2081 			xfer->endpoint->is_synced = 1;
2082 			temp.do_isoc_sync = 1;
2083 
2084 			DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next);
2085 		}
2086 
2087 		/* compute isochronous completion time */
2088 
2089 		y = XHCI_MFINDEX_GET(xfer->endpoint->isoc_next - (x & ~7));
2090 
2091 		xfer->isoc_time_complete =
2092 		    usb_isoc_time_expand(&temp.sc->sc_bus, x / 8) +
2093 		    (y / 8) + (((xfer->nframes << shift) + 7) / 8);
2094 
2095 		x = 0;
2096 		temp.isoc_frame = xfer->endpoint->isoc_next;
2097 		temp.trb_type = XHCI_TRB_TYPE_ISOCH;
2098 
2099 		xfer->endpoint->isoc_next += xfer->nframes << shift;
2100 
2101 	} else if (xfer->flags_int.control_xfr) {
2102 
2103 		/* check if we should prepend a setup message */
2104 
2105 		if (xfer->flags_int.control_hdr) {
2106 
2107 			temp.len = xfer->frlengths[0];
2108 			temp.pc = xfer->frbuffers + 0;
2109 			temp.shortpkt = temp.len ? 1 : 0;
2110 			temp.trb_type = XHCI_TRB_TYPE_SETUP_STAGE;
2111 			temp.direction = 0;
2112 
2113 			/* check for last frame */
2114 			if (xfer->nframes == 1) {
2115 				/* no STATUS stage yet, SETUP is last */
2116 				if (xfer->flags_int.control_act)
2117 					temp.last_frame = 1;
2118 			}
2119 
2120 			xhci_setup_generic_chain_sub(&temp);
2121 		}
2122 		x = 1;
2123 		mult = 1;
2124 		temp.isoc_delta = 0;
2125 		temp.isoc_frame = 0;
2126 		temp.trb_type = xfer->flags_int.control_did_data ?
2127 		    XHCI_TRB_TYPE_NORMAL : XHCI_TRB_TYPE_DATA_STAGE;
2128 	} else {
2129 		x = 0;
2130 		mult = 1;
2131 		temp.isoc_delta = 0;
2132 		temp.isoc_frame = 0;
2133 		temp.trb_type = XHCI_TRB_TYPE_NORMAL;
2134 	}
2135 
2136 	if (x != xfer->nframes) {
2137                 /* set up page_cache pointer */
2138                 temp.pc = xfer->frbuffers + x;
2139 		/* set endpoint direction */
2140 		temp.direction = UE_GET_DIR(xfer->endpointno);
2141 	}
2142 
2143 	while (x != xfer->nframes) {
2144 
2145 		/* DATA0 / DATA1 message */
2146 
2147 		temp.len = xfer->frlengths[x];
2148 		temp.step_td = ((xfer->endpointno & UE_DIR_IN) &&
2149 		    x != 0 && temp.multishort == 0);
2150 
2151 		x++;
2152 
2153 		if (x == xfer->nframes) {
2154 			if (xfer->flags_int.control_xfr) {
2155 				/* no STATUS stage yet, DATA is last */
2156 				if (xfer->flags_int.control_act)
2157 					temp.last_frame = 1;
2158 			} else {
2159 				temp.last_frame = 1;
2160 			}
2161 		}
2162 		if (temp.len == 0) {
2163 
2164 			/* make sure that we send an USB packet */
2165 
2166 			temp.shortpkt = 0;
2167 
2168 			temp.tbc = 0;
2169 			temp.tlbpc = mult - 1;
2170 
2171 		} else if (xfer->flags_int.isochronous_xfr) {
2172 
2173 			uint8_t tdpc;
2174 
2175 			/*
2176 			 * Isochronous transfers don't have short
2177 			 * packet termination:
2178 			 */
2179 
2180 			temp.shortpkt = 1;
2181 
2182 			/* isochronous transfers have a transfer limit */
2183 
2184 			if (temp.len > xfer->max_frame_size)
2185 				temp.len = xfer->max_frame_size;
2186 
2187 			/* compute TD packet count */
2188 			tdpc = howmany(temp.len, xfer->max_packet_size);
2189 
2190 			temp.tbc = howmany(tdpc, mult) - 1;
2191 			temp.tlbpc = (tdpc % mult);
2192 
2193 			if (temp.tlbpc == 0)
2194 				temp.tlbpc = mult - 1;
2195 			else
2196 				temp.tlbpc--;
2197 		} else {
2198 
2199 			/* regular data transfer */
2200 
2201 			temp.shortpkt = xfer->flags.force_short_xfer ? 0 : 1;
2202 		}
2203 
2204 		xhci_setup_generic_chain_sub(&temp);
2205 
2206 		if (xfer->flags_int.isochronous_xfr) {
2207 			temp.offset += xfer->frlengths[x - 1];
2208 			temp.isoc_frame += temp.isoc_delta;
2209 		} else {
2210 			/* get next Page Cache pointer */
2211 			temp.pc = xfer->frbuffers + x;
2212 		}
2213 	}
2214 
2215 	/* check if we should append a status stage */
2216 
2217 	if (xfer->flags_int.control_xfr &&
2218 	    !xfer->flags_int.control_act) {
2219 
2220 		/*
2221 		 * Send a DATA1 message and invert the current
2222 		 * endpoint direction.
2223 		 */
2224 		temp.step_td = (xfer->nframes != 0);
2225 		temp.direction = UE_GET_DIR(xfer->endpointno) ^ UE_DIR_IN;
2226 		temp.len = 0;
2227 		temp.pc = NULL;
2228 		temp.shortpkt = 0;
2229 		temp.last_frame = 1;
2230 		temp.trb_type = XHCI_TRB_TYPE_STATUS_STAGE;
2231 
2232 		xhci_setup_generic_chain_sub(&temp);
2233 	}
2234 
2235 	td = temp.td;
2236 
2237 	/* must have at least one frame! */
2238 
2239 	xfer->td_transfer_last = td;
2240 
2241 	DPRINTF("first=%p last=%p\n", xfer->td_transfer_first, td);
2242 }
2243 
2244 static void
2245 xhci_set_slot_pointer(struct xhci_softc *sc, uint8_t index, uint64_t dev_addr)
2246 {
2247 	struct usb_page_search buf_res;
2248 	struct xhci_dev_ctx_addr *pdctxa;
2249 
2250 	usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
2251 
2252 	pdctxa = buf_res.buffer;
2253 
2254 	DPRINTF("addr[%u]=0x%016llx\n", index, (long long)dev_addr);
2255 
2256 	pdctxa->qwBaaDevCtxAddr[index] = htole64(dev_addr);
2257 
2258 	usb_pc_cpu_flush(&sc->sc_hw.ctx_pc);
2259 }
2260 
2261 static usb_error_t
2262 xhci_configure_mask(struct usb_device *udev, uint32_t mask, uint8_t drop)
2263 {
2264 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2265 	struct usb_page_search buf_inp;
2266 	struct xhci_input_dev_ctx *pinp;
2267 	uint32_t temp;
2268 	uint8_t index;
2269 	uint8_t x;
2270 
2271 	index = udev->controller_slot_id;
2272 
2273 	usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2274 
2275 	pinp = buf_inp.buffer;
2276 
2277 	if (drop) {
2278 		mask &= XHCI_INCTX_NON_CTRL_MASK;
2279 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0, mask);
2280 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, 0);
2281 	} else {
2282 		/*
2283 		 * Some hardware requires that we drop the endpoint
2284 		 * context before adding it again:
2285 		 */
2286 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0,
2287 		    mask & XHCI_INCTX_NON_CTRL_MASK);
2288 
2289 		/* Add new endpoint context */
2290 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, mask);
2291 
2292 		/* find most significant set bit */
2293 		for (x = 31; x != 1; x--) {
2294 			if (mask & (1 << x))
2295 				break;
2296 		}
2297 
2298 		/* adjust */
2299 		x--;
2300 
2301 		/* figure out the maximum number of contexts */
2302 		if (x > sc->sc_hw.devs[index].context_num)
2303 			sc->sc_hw.devs[index].context_num = x;
2304 		else
2305 			x = sc->sc_hw.devs[index].context_num;
2306 
2307 		/* update number of contexts */
2308 		temp = xhci_ctx_get_le32(sc, &pinp->ctx_slot.dwSctx0);
2309 		temp &= ~XHCI_SCTX_0_CTX_NUM_SET(31);
2310 		temp |= XHCI_SCTX_0_CTX_NUM_SET(x + 1);
2311 		xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2312 	}
2313 	usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2314 	return (0);
2315 }
2316 
2317 static usb_error_t
2318 xhci_configure_endpoint(struct usb_device *udev,
2319     struct usb_endpoint_descriptor *edesc, struct xhci_endpoint_ext *pepext,
2320     uint16_t interval, uint8_t max_packet_count,
2321     uint8_t mult, uint8_t fps_shift, uint16_t max_packet_size,
2322     uint16_t max_frame_size, uint8_t ep_mode)
2323 {
2324 	struct usb_page_search buf_inp;
2325 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2326 	struct xhci_input_dev_ctx *pinp;
2327 	uint64_t ring_addr = pepext->physaddr;
2328 	uint32_t temp;
2329 	uint8_t index;
2330 	uint8_t epno;
2331 	uint8_t type;
2332 
2333 	index = udev->controller_slot_id;
2334 
2335 	usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2336 
2337 	pinp = buf_inp.buffer;
2338 
2339 	epno = edesc->bEndpointAddress;
2340 	type = edesc->bmAttributes & UE_XFERTYPE;
2341 
2342 	if (type == UE_CONTROL)
2343 		epno |= UE_DIR_IN;
2344 
2345 	epno = XHCI_EPNO2EPID(epno);
2346 
2347  	if (epno == 0)
2348 		return (USB_ERR_NO_PIPE);		/* invalid */
2349 
2350 	if (max_packet_count == 0)
2351 		return (USB_ERR_BAD_BUFSIZE);
2352 
2353 	max_packet_count--;
2354 
2355 	if (mult == 0)
2356 		return (USB_ERR_BAD_BUFSIZE);
2357 
2358 	/* store endpoint mode */
2359 	pepext->trb_ep_mode = ep_mode;
2360 	/* store bMaxPacketSize for control endpoints */
2361 	pepext->trb_ep_maxp = edesc->wMaxPacketSize[0];
2362 	usb_pc_cpu_flush(pepext->page_cache);
2363 
2364 	if (ep_mode == USB_EP_MODE_STREAMS) {
2365 		temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2366 		    XHCI_EPCTX_0_MAXP_STREAMS_SET(XHCI_MAX_STREAMS_LOG - 1) |
2367 		    XHCI_EPCTX_0_LSA_SET(1);
2368 
2369 		ring_addr += sizeof(struct xhci_trb) *
2370 		    XHCI_MAX_TRANSFERS * XHCI_MAX_STREAMS;
2371 	} else {
2372 		temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2373 		    XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
2374 		    XHCI_EPCTX_0_LSA_SET(0);
2375 
2376 		ring_addr |= XHCI_EPCTX_2_DCS_SET(1);
2377 	}
2378 
2379 	switch (udev->speed) {
2380 	case USB_SPEED_FULL:
2381 	case USB_SPEED_LOW:
2382 		/* 1ms -> 125us */
2383 		fps_shift += 3;
2384 		break;
2385 	default:
2386 		break;
2387 	}
2388 
2389 	switch (type) {
2390 	case UE_INTERRUPT:
2391 		if (fps_shift > 3)
2392 			fps_shift--;
2393 		temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2394 		break;
2395 	case UE_ISOCHRONOUS:
2396 		temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2397 
2398 		switch (udev->speed) {
2399 		case USB_SPEED_SUPER:
2400 			if (mult > 3)
2401 				mult = 3;
2402 			temp |= XHCI_EPCTX_0_MULT_SET(mult - 1);
2403 			max_packet_count /= mult;
2404 			break;
2405 		default:
2406 			break;
2407 		}
2408 		break;
2409 	default:
2410 		break;
2411 	}
2412 
2413 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx0, temp);
2414 
2415 	temp =
2416 	    XHCI_EPCTX_1_HID_SET(0) |
2417 	    XHCI_EPCTX_1_MAXB_SET(max_packet_count) |
2418 	    XHCI_EPCTX_1_MAXP_SIZE_SET(max_packet_size);
2419 
2420 	/*
2421 	 * Always enable the "three strikes and you are gone" feature
2422 	 * except for ISOCHRONOUS endpoints. This is suggested by
2423 	 * section 4.3.3 in the XHCI specification about device slot
2424 	 * initialisation.
2425 	 */
2426 	if (type != UE_ISOCHRONOUS)
2427 		temp |= XHCI_EPCTX_1_CERR_SET(3);
2428 
2429 	switch (type) {
2430 	case UE_CONTROL:
2431 		temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2432 		break;
2433 	case UE_ISOCHRONOUS:
2434 		temp |= XHCI_EPCTX_1_EPTYPE_SET(1);
2435 		break;
2436 	case UE_BULK:
2437 		temp |= XHCI_EPCTX_1_EPTYPE_SET(2);
2438 		break;
2439 	default:
2440 		temp |= XHCI_EPCTX_1_EPTYPE_SET(3);
2441 		break;
2442 	}
2443 
2444 	/* check for IN direction */
2445 	if (epno & 1)
2446 		temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2447 
2448 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx1, temp);
2449 	xhci_ctx_set_le64(sc, &pinp->ctx_ep[epno - 1].qwEpCtx2, ring_addr);
2450 
2451 	switch (edesc->bmAttributes & UE_XFERTYPE) {
2452 	case UE_INTERRUPT:
2453 	case UE_ISOCHRONOUS:
2454 		temp = XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(max_frame_size) |
2455 		    XHCI_EPCTX_4_AVG_TRB_LEN_SET(MIN(XHCI_PAGE_SIZE,
2456 		    max_frame_size));
2457 		break;
2458 	case UE_CONTROL:
2459 		temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8);
2460 		break;
2461 	default:
2462 		temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(XHCI_PAGE_SIZE);
2463 		break;
2464 	}
2465 
2466 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx4, temp);
2467 
2468 #ifdef USB_DEBUG
2469 	xhci_dump_endpoint(sc, &pinp->ctx_ep[epno - 1]);
2470 #endif
2471 	usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2472 
2473 	return (0);		/* success */
2474 }
2475 
2476 static usb_error_t
2477 xhci_configure_endpoint_by_xfer(struct usb_xfer *xfer)
2478 {
2479 	struct xhci_endpoint_ext *pepext;
2480 	struct usb_endpoint_ss_comp_descriptor *ecomp;
2481 	usb_stream_t x;
2482 
2483 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2484 	    xfer->endpoint->edesc);
2485 
2486 	ecomp = xfer->endpoint->ecomp;
2487 
2488 	for (x = 0; x != XHCI_MAX_STREAMS; x++) {
2489 		uint64_t temp;
2490 
2491 		/* halt any transfers */
2492 		pepext->trb[x * XHCI_MAX_TRANSFERS].dwTrb3 = 0;
2493 
2494 		/* compute start of TRB ring for stream "x" */
2495 		temp = pepext->physaddr +
2496 		    (x * XHCI_MAX_TRANSFERS * sizeof(struct xhci_trb)) +
2497 		    XHCI_SCTX_0_SCT_SEC_TR_RING;
2498 
2499 		/* make tree structure */
2500 		pepext->trb[(XHCI_MAX_TRANSFERS *
2501 		    XHCI_MAX_STREAMS) + x].qwTrb0 = htole64(temp);
2502 
2503 		/* reserved fields */
2504 		pepext->trb[(XHCI_MAX_TRANSFERS *
2505                     XHCI_MAX_STREAMS) + x].dwTrb2 = 0;
2506 		pepext->trb[(XHCI_MAX_TRANSFERS *
2507 		    XHCI_MAX_STREAMS) + x].dwTrb3 = 0;
2508 	}
2509 	usb_pc_cpu_flush(pepext->page_cache);
2510 
2511 	return (xhci_configure_endpoint(xfer->xroot->udev,
2512 	    xfer->endpoint->edesc, pepext,
2513 	    xfer->interval, xfer->max_packet_count,
2514 	    (ecomp != NULL) ? UE_GET_SS_ISO_MULT(ecomp->bmAttributes) + 1 : 1,
2515 	    usbd_xfer_get_fps_shift(xfer), xfer->max_packet_size,
2516 	    xfer->max_frame_size, xfer->endpoint->ep_mode));
2517 }
2518 
2519 static usb_error_t
2520 xhci_configure_device(struct usb_device *udev)
2521 {
2522 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2523 	struct usb_page_search buf_inp;
2524 	struct usb_page_cache *pcinp;
2525 	struct xhci_input_dev_ctx *pinp;
2526 	struct usb_device *hubdev;
2527 	uint32_t temp;
2528 	uint32_t route;
2529 	uint32_t rh_port;
2530 	uint8_t is_hub;
2531 	uint8_t index;
2532 	uint8_t depth;
2533 
2534 	index = udev->controller_slot_id;
2535 
2536 	DPRINTF("index=%u\n", index);
2537 
2538 	pcinp = &sc->sc_hw.devs[index].input_pc;
2539 
2540 	usbd_get_page(pcinp, 0, &buf_inp);
2541 
2542 	pinp = buf_inp.buffer;
2543 
2544 	rh_port = 0;
2545 	route = 0;
2546 
2547 	/* figure out route string and root HUB port number */
2548 
2549 	for (hubdev = udev; hubdev != NULL; hubdev = hubdev->parent_hub) {
2550 
2551 		if (hubdev->parent_hub == NULL)
2552 			break;
2553 
2554 		depth = hubdev->parent_hub->depth;
2555 
2556 		/*
2557 		 * NOTE: HS/FS/LS devices and the SS root HUB can have
2558 		 * more than 15 ports
2559 		 */
2560 
2561 		rh_port = hubdev->port_no;
2562 
2563 		if (depth == 0)
2564 			break;
2565 
2566 		if (rh_port > 15)
2567 			rh_port = 15;
2568 
2569 		if (depth < 6)
2570 			route |= rh_port << (4 * (depth - 1));
2571 	}
2572 
2573 	DPRINTF("Route=0x%08x\n", route);
2574 
2575 	temp = XHCI_SCTX_0_ROUTE_SET(route) |
2576 	    XHCI_SCTX_0_CTX_NUM_SET(
2577 	    sc->sc_hw.devs[index].context_num + 1);
2578 
2579 	switch (udev->speed) {
2580 	case USB_SPEED_LOW:
2581 		temp |= XHCI_SCTX_0_SPEED_SET(2);
2582 		if (udev->parent_hs_hub != NULL &&
2583 		    udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2584 		    UDPROTO_HSHUBMTT) {
2585 			DPRINTF("Device inherits MTT\n");
2586 			temp |= XHCI_SCTX_0_MTT_SET(1);
2587 		}
2588 		break;
2589 	case USB_SPEED_HIGH:
2590 		temp |= XHCI_SCTX_0_SPEED_SET(3);
2591 		if (sc->sc_hw.devs[index].nports != 0 &&
2592 		    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) {
2593 			DPRINTF("HUB supports MTT\n");
2594 			temp |= XHCI_SCTX_0_MTT_SET(1);
2595 		}
2596 		break;
2597 	case USB_SPEED_FULL:
2598 		temp |= XHCI_SCTX_0_SPEED_SET(1);
2599 		if (udev->parent_hs_hub != NULL &&
2600 		    udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2601 		    UDPROTO_HSHUBMTT) {
2602 			DPRINTF("Device inherits MTT\n");
2603 			temp |= XHCI_SCTX_0_MTT_SET(1);
2604 		}
2605 		break;
2606 	default:
2607 		temp |= XHCI_SCTX_0_SPEED_SET(4);
2608 		break;
2609 	}
2610 
2611 	is_hub = sc->sc_hw.devs[index].nports != 0 &&
2612 	    (udev->speed == USB_SPEED_SUPER ||
2613 	    udev->speed == USB_SPEED_HIGH);
2614 
2615 	if (is_hub)
2616 		temp |= XHCI_SCTX_0_HUB_SET(1);
2617 
2618 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2619 
2620 	temp = XHCI_SCTX_1_RH_PORT_SET(rh_port);
2621 
2622 	if (is_hub) {
2623 		temp |= XHCI_SCTX_1_NUM_PORTS_SET(
2624 		    sc->sc_hw.devs[index].nports);
2625 	}
2626 
2627 	switch (udev->speed) {
2628 	case USB_SPEED_SUPER:
2629 		switch (sc->sc_hw.devs[index].state) {
2630 		case XHCI_ST_ADDRESSED:
2631 		case XHCI_ST_CONFIGURED:
2632 			/* enable power save */
2633 			temp |= XHCI_SCTX_1_MAX_EL_SET(sc->sc_exit_lat_max);
2634 			break;
2635 		default:
2636 			/* disable power save */
2637 			break;
2638 		}
2639 		break;
2640 	default:
2641 		break;
2642 	}
2643 
2644 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx1, temp);
2645 
2646 	temp = XHCI_SCTX_2_IRQ_TARGET_SET(0);
2647 
2648 	if (is_hub) {
2649 		temp |= XHCI_SCTX_2_TT_THINK_TIME_SET(
2650 		    sc->sc_hw.devs[index].tt);
2651 	}
2652 
2653 	hubdev = udev->parent_hs_hub;
2654 
2655 	/* check if we should activate the transaction translator */
2656 	switch (udev->speed) {
2657 	case USB_SPEED_FULL:
2658 	case USB_SPEED_LOW:
2659 		if (hubdev != NULL) {
2660 			temp |= XHCI_SCTX_2_TT_HUB_SID_SET(
2661 			    hubdev->controller_slot_id);
2662 			temp |= XHCI_SCTX_2_TT_PORT_NUM_SET(
2663 			    udev->hs_port_no);
2664 		}
2665 		break;
2666 	default:
2667 		break;
2668 	}
2669 
2670 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx2, temp);
2671 
2672 	/*
2673 	 * These fields should be initialized to zero, according to
2674 	 * XHCI section 6.2.2 - slot context:
2675 	 */
2676 	temp = XHCI_SCTX_3_DEV_ADDR_SET(0) |
2677 	    XHCI_SCTX_3_SLOT_STATE_SET(0);
2678 
2679 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx3, temp);
2680 
2681 #ifdef USB_DEBUG
2682 	xhci_dump_device(sc, &pinp->ctx_slot);
2683 #endif
2684 	usb_pc_cpu_flush(pcinp);
2685 
2686 	return (0);		/* success */
2687 }
2688 
2689 static usb_error_t
2690 xhci_alloc_device_ext(struct usb_device *udev)
2691 {
2692 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2693 	struct usb_page_search buf_dev;
2694 	struct usb_page_search buf_ep;
2695 	struct xhci_trb *trb;
2696 	struct usb_page_cache *pc;
2697 	struct usb_page *pg;
2698 	uint64_t addr;
2699 	uint8_t index;
2700 	uint8_t i;
2701 
2702 	index = udev->controller_slot_id;
2703 
2704 	pc = &sc->sc_hw.devs[index].device_pc;
2705 	pg = &sc->sc_hw.devs[index].device_pg;
2706 
2707 	/* need to initialize the page cache */
2708 	pc->tag_parent = sc->sc_bus.dma_parent_tag;
2709 
2710 	if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2711 	    (2 * sizeof(struct xhci_dev_ctx)) :
2712 	    sizeof(struct xhci_dev_ctx), XHCI_PAGE_SIZE))
2713 		goto error;
2714 
2715 	usbd_get_page(pc, 0, &buf_dev);
2716 
2717 	pc = &sc->sc_hw.devs[index].input_pc;
2718 	pg = &sc->sc_hw.devs[index].input_pg;
2719 
2720 	/* need to initialize the page cache */
2721 	pc->tag_parent = sc->sc_bus.dma_parent_tag;
2722 
2723 	if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2724 	    (2 * sizeof(struct xhci_input_dev_ctx)) :
2725 	    sizeof(struct xhci_input_dev_ctx), XHCI_PAGE_SIZE)) {
2726 		goto error;
2727 	}
2728 
2729 	/* initialize all endpoint LINK TRBs */
2730 
2731 	for (i = 0; i != XHCI_MAX_ENDPOINTS; i++) {
2732 
2733 		pc = &sc->sc_hw.devs[index].endpoint_pc[i];
2734 		pg = &sc->sc_hw.devs[index].endpoint_pg[i];
2735 
2736 		/* need to initialize the page cache */
2737 		pc->tag_parent = sc->sc_bus.dma_parent_tag;
2738 
2739 		if (usb_pc_alloc_mem(pc, pg,
2740 		    sizeof(struct xhci_dev_endpoint_trbs), XHCI_TRB_ALIGN)) {
2741 			goto error;
2742 		}
2743 
2744 		/* lookup endpoint TRB ring */
2745 		usbd_get_page(pc, 0, &buf_ep);
2746 
2747 		/* get TRB pointer */
2748 		trb = buf_ep.buffer;
2749 		trb += XHCI_MAX_TRANSFERS - 1;
2750 
2751 		/* get TRB start address */
2752 		addr = buf_ep.physaddr;
2753 
2754 		/* create LINK TRB */
2755 		trb->qwTrb0 = htole64(addr);
2756 		trb->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2757 		trb->dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2758 		    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2759 
2760 		usb_pc_cpu_flush(pc);
2761 	}
2762 
2763 	xhci_set_slot_pointer(sc, index, buf_dev.physaddr);
2764 
2765 	return (0);
2766 
2767 error:
2768 	xhci_free_device_ext(udev);
2769 
2770 	return (USB_ERR_NOMEM);
2771 }
2772 
2773 static void
2774 xhci_free_device_ext(struct usb_device *udev)
2775 {
2776 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2777 	uint8_t index;
2778 	uint8_t i;
2779 
2780 	index = udev->controller_slot_id;
2781 	xhci_set_slot_pointer(sc, index, 0);
2782 
2783 	usb_pc_free_mem(&sc->sc_hw.devs[index].device_pc);
2784 	usb_pc_free_mem(&sc->sc_hw.devs[index].input_pc);
2785 	for (i = 0; i != XHCI_MAX_ENDPOINTS; i++)
2786 		usb_pc_free_mem(&sc->sc_hw.devs[index].endpoint_pc[i]);
2787 }
2788 
2789 static struct xhci_endpoint_ext *
2790 xhci_get_endpoint_ext(struct usb_device *udev, struct usb_endpoint_descriptor *edesc)
2791 {
2792 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2793 	struct xhci_endpoint_ext *pepext;
2794 	struct usb_page_cache *pc;
2795 	struct usb_page_search buf_ep;
2796 	uint8_t epno;
2797 	uint8_t index;
2798 
2799 	epno = edesc->bEndpointAddress;
2800 	if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
2801 		epno |= UE_DIR_IN;
2802 
2803 	epno = XHCI_EPNO2EPID(epno);
2804 
2805 	index = udev->controller_slot_id;
2806 
2807 	pc = &sc->sc_hw.devs[index].endpoint_pc[epno];
2808 
2809 	usbd_get_page(pc, 0, &buf_ep);
2810 
2811 	pepext = &sc->sc_hw.devs[index].endp[epno];
2812 	pepext->page_cache = pc;
2813 	pepext->trb = buf_ep.buffer;
2814 	pepext->physaddr = buf_ep.physaddr;
2815 
2816 	return (pepext);
2817 }
2818 
2819 static void
2820 xhci_endpoint_doorbell(struct usb_xfer *xfer)
2821 {
2822 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2823 	uint8_t epno;
2824 	uint8_t index;
2825 
2826 	epno = xfer->endpointno;
2827 	if (xfer->flags_int.control_xfr)
2828 		epno |= UE_DIR_IN;
2829 
2830 	epno = XHCI_EPNO2EPID(epno);
2831 	index = xfer->xroot->udev->controller_slot_id;
2832 
2833 	if (xfer->xroot->udev->flags.self_suspended == 0) {
2834 		XWRITE4(sc, door, XHCI_DOORBELL(index),
2835 		    epno | XHCI_DB_SID_SET(xfer->stream_id));
2836 	}
2837 }
2838 
2839 static void
2840 xhci_transfer_remove(struct usb_xfer *xfer, usb_error_t error)
2841 {
2842 	struct xhci_endpoint_ext *pepext;
2843 
2844 	if (xfer->flags_int.bandwidth_reclaimed) {
2845 		xfer->flags_int.bandwidth_reclaimed = 0;
2846 
2847 		pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2848 		    xfer->endpoint->edesc);
2849 
2850 		pepext->trb_used[xfer->stream_id]--;
2851 
2852 		pepext->xfer[xfer->qh_pos] = NULL;
2853 
2854 		if (error && pepext->trb_running != 0) {
2855 			pepext->trb_halted = 1;
2856 			pepext->trb_running = 0;
2857 		}
2858 	}
2859 }
2860 
2861 static usb_error_t
2862 xhci_transfer_insert(struct usb_xfer *xfer)
2863 {
2864 	struct xhci_td *td_first;
2865 	struct xhci_td *td_last;
2866 	struct xhci_trb *trb_link;
2867 	struct xhci_endpoint_ext *pepext;
2868 	uint64_t addr;
2869 	usb_stream_t id;
2870 	uint8_t i;
2871 	uint8_t inext;
2872 	uint8_t trb_limit;
2873 
2874 	DPRINTFN(8, "\n");
2875 
2876 	id = xfer->stream_id;
2877 
2878 	/* check if already inserted */
2879 	if (xfer->flags_int.bandwidth_reclaimed) {
2880 		DPRINTFN(8, "Already in schedule\n");
2881 		return (0);
2882 	}
2883 
2884 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2885 	    xfer->endpoint->edesc);
2886 
2887 	td_first = xfer->td_transfer_first;
2888 	td_last = xfer->td_transfer_last;
2889 	addr = pepext->physaddr;
2890 
2891 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2892 	case UE_CONTROL:
2893 	case UE_INTERRUPT:
2894 		/* single buffered */
2895 		trb_limit = 1;
2896 		break;
2897 	default:
2898 		/* multi buffered */
2899 		trb_limit = (XHCI_MAX_TRANSFERS - 2);
2900 		break;
2901 	}
2902 
2903 	if (pepext->trb_used[id] >= trb_limit) {
2904 		DPRINTFN(8, "Too many TDs queued.\n");
2905 		return (USB_ERR_NOMEM);
2906 	}
2907 
2908 	/* check if bMaxPacketSize changed */
2909 	if (xfer->flags_int.control_xfr != 0 &&
2910 	    pepext->trb_ep_maxp != xfer->endpoint->edesc->wMaxPacketSize[0]) {
2911 
2912 		DPRINTFN(8, "Reconfigure control endpoint\n");
2913 
2914 		/* force driver to reconfigure endpoint */
2915 		pepext->trb_halted = 1;
2916 		pepext->trb_running = 0;
2917 	}
2918 
2919 	/* check for stopped condition, after putting transfer on interrupt queue */
2920 	if (pepext->trb_running == 0) {
2921 		struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2922 
2923 		DPRINTFN(8, "Not running\n");
2924 
2925 		/* start configuration */
2926 		(void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
2927 		    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2928 		return (0);
2929 	}
2930 
2931 	pepext->trb_used[id]++;
2932 
2933 	/* get current TRB index */
2934 	i = pepext->trb_index[id];
2935 
2936 	/* get next TRB index */
2937 	inext = (i + 1);
2938 
2939 	/* the last entry of the ring is a hardcoded link TRB */
2940 	if (inext >= (XHCI_MAX_TRANSFERS - 1))
2941 		inext = 0;
2942 
2943 	/* store next TRB index, before stream ID offset is added */
2944 	pepext->trb_index[id] = inext;
2945 
2946 	/* offset for stream */
2947 	i += id * XHCI_MAX_TRANSFERS;
2948 	inext += id * XHCI_MAX_TRANSFERS;
2949 
2950 	/* compute terminating return address */
2951 	addr += (inext * sizeof(struct xhci_trb));
2952 
2953 	/* compute link TRB pointer */
2954 	trb_link = td_last->td_trb + td_last->ntrb;
2955 
2956 	/* update next pointer of last link TRB */
2957 	trb_link->qwTrb0 = htole64(addr);
2958 	trb_link->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2959 	trb_link->dwTrb3 = htole32(XHCI_TRB_3_IOC_BIT |
2960 	    XHCI_TRB_3_CYCLE_BIT |
2961 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2962 
2963 #ifdef USB_DEBUG
2964 	xhci_dump_trb(&td_last->td_trb[td_last->ntrb]);
2965 #endif
2966 	usb_pc_cpu_flush(td_last->page_cache);
2967 
2968 	/* write ahead chain end marker */
2969 
2970 	pepext->trb[inext].qwTrb0 = 0;
2971 	pepext->trb[inext].dwTrb2 = 0;
2972 	pepext->trb[inext].dwTrb3 = 0;
2973 
2974 	/* update next pointer of link TRB */
2975 
2976 	pepext->trb[i].qwTrb0 = htole64((uint64_t)td_first->td_self);
2977 	pepext->trb[i].dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2978 
2979 #ifdef USB_DEBUG
2980 	xhci_dump_trb(&pepext->trb[i]);
2981 #endif
2982 	usb_pc_cpu_flush(pepext->page_cache);
2983 
2984 	/* toggle cycle bit which activates the transfer chain */
2985 
2986 	pepext->trb[i].dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2987 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2988 
2989 	usb_pc_cpu_flush(pepext->page_cache);
2990 
2991 	DPRINTF("qh_pos = %u\n", i);
2992 
2993 	pepext->xfer[i] = xfer;
2994 
2995 	xfer->qh_pos = i;
2996 
2997 	xfer->flags_int.bandwidth_reclaimed = 1;
2998 
2999 	xhci_endpoint_doorbell(xfer);
3000 
3001 	return (0);
3002 }
3003 
3004 static void
3005 xhci_root_intr(struct xhci_softc *sc)
3006 {
3007 	uint16_t i;
3008 
3009 	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3010 
3011 	/* clear any old interrupt data */
3012 	memset(sc->sc_hub_idata, 0, sizeof(sc->sc_hub_idata));
3013 
3014 	for (i = 1; i <= sc->sc_noport; i++) {
3015 		/* pick out CHANGE bits from the status register */
3016 		if (XREAD4(sc, oper, XHCI_PORTSC(i)) & (
3017 		    XHCI_PS_CSC | XHCI_PS_PEC |
3018 		    XHCI_PS_OCC | XHCI_PS_WRC |
3019 		    XHCI_PS_PRC | XHCI_PS_PLC |
3020 		    XHCI_PS_CEC)) {
3021 			sc->sc_hub_idata[i / 8] |= 1 << (i % 8);
3022 			DPRINTF("port %d changed\n", i);
3023 		}
3024 	}
3025 	uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
3026 	    sizeof(sc->sc_hub_idata));
3027 }
3028 
3029 /*------------------------------------------------------------------------*
3030  *	xhci_device_done - XHCI done handler
3031  *
3032  * NOTE: This function can be called two times in a row on
3033  * the same USB transfer. From close and from interrupt.
3034  *------------------------------------------------------------------------*/
3035 static void
3036 xhci_device_done(struct usb_xfer *xfer, usb_error_t error)
3037 {
3038 	DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
3039 	    xfer, xfer->endpoint, error);
3040 
3041 	/* remove transfer from HW queue */
3042 	xhci_transfer_remove(xfer, error);
3043 
3044 	/* dequeue transfer and start next transfer */
3045 	usbd_transfer_done(xfer, error);
3046 }
3047 
3048 /*------------------------------------------------------------------------*
3049  * XHCI data transfer support (generic type)
3050  *------------------------------------------------------------------------*/
3051 static void
3052 xhci_device_generic_open(struct usb_xfer *xfer)
3053 {
3054 	if (xfer->flags_int.isochronous_xfr) {
3055 		switch (xfer->xroot->udev->speed) {
3056 		case USB_SPEED_FULL:
3057 			break;
3058 		default:
3059 			usb_hs_bandwidth_alloc(xfer);
3060 			break;
3061 		}
3062 	}
3063 }
3064 
3065 static void
3066 xhci_device_generic_close(struct usb_xfer *xfer)
3067 {
3068 	DPRINTF("\n");
3069 
3070 	xhci_device_done(xfer, USB_ERR_CANCELLED);
3071 
3072 	if (xfer->flags_int.isochronous_xfr) {
3073 		switch (xfer->xroot->udev->speed) {
3074 		case USB_SPEED_FULL:
3075 			break;
3076 		default:
3077 			usb_hs_bandwidth_free(xfer);
3078 			break;
3079 		}
3080 	}
3081 }
3082 
3083 static void
3084 xhci_device_generic_multi_enter(struct usb_endpoint *ep,
3085     usb_stream_t stream_id, struct usb_xfer *enter_xfer)
3086 {
3087 	struct usb_xfer *xfer;
3088 
3089 	/* check if there is a current transfer */
3090 	xfer = ep->endpoint_q[stream_id].curr;
3091 	if (xfer == NULL)
3092 		return;
3093 
3094 	/*
3095 	 * Check if the current transfer is started and then pickup
3096 	 * the next one, if any. Else wait for next start event due to
3097 	 * block on failure feature.
3098 	 */
3099 	if (!xfer->flags_int.bandwidth_reclaimed)
3100 		return;
3101 
3102 	xfer = TAILQ_FIRST(&ep->endpoint_q[stream_id].head);
3103 	if (xfer == NULL) {
3104 		/*
3105 		 * In case of enter we have to consider that the
3106 		 * transfer is queued by the USB core after the enter
3107 		 * method is called.
3108 		 */
3109 		xfer = enter_xfer;
3110 
3111 		if (xfer == NULL)
3112 			return;
3113 	}
3114 
3115 	/* try to multi buffer */
3116 	xhci_transfer_insert(xfer);
3117 }
3118 
3119 static void
3120 xhci_device_generic_enter(struct usb_xfer *xfer)
3121 {
3122 	DPRINTF("\n");
3123 
3124 	/* set up TD's and QH */
3125 	xhci_setup_generic_chain(xfer);
3126 
3127 	xhci_device_generic_multi_enter(xfer->endpoint,
3128 	    xfer->stream_id, xfer);
3129 }
3130 
3131 static void
3132 xhci_device_generic_start(struct usb_xfer *xfer)
3133 {
3134 	DPRINTF("\n");
3135 
3136 	/* try to insert xfer on HW queue */
3137 	xhci_transfer_insert(xfer);
3138 
3139 	/* try to multi buffer */
3140 	xhci_device_generic_multi_enter(xfer->endpoint,
3141 	    xfer->stream_id, NULL);
3142 
3143 	/* add transfer last on interrupt queue */
3144 	usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
3145 
3146 	/* start timeout, if any */
3147 	if (xfer->timeout != 0)
3148 		usbd_transfer_timeout_ms(xfer, &xhci_timeout, xfer->timeout);
3149 }
3150 
3151 static const struct usb_pipe_methods xhci_device_generic_methods =
3152 {
3153 	.open = xhci_device_generic_open,
3154 	.close = xhci_device_generic_close,
3155 	.enter = xhci_device_generic_enter,
3156 	.start = xhci_device_generic_start,
3157 };
3158 
3159 /*------------------------------------------------------------------------*
3160  * xhci root HUB support
3161  *------------------------------------------------------------------------*
3162  * Simulate a hardware HUB by handling all the necessary requests.
3163  *------------------------------------------------------------------------*/
3164 
3165 #define	HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) }
3166 
3167 static const
3168 struct usb_device_descriptor xhci_devd =
3169 {
3170 	.bLength = sizeof(xhci_devd),
3171 	.bDescriptorType = UDESC_DEVICE,	/* type */
3172 	HSETW(.bcdUSB, 0x0300),			/* USB version */
3173 	.bDeviceClass = UDCLASS_HUB,		/* class */
3174 	.bDeviceSubClass = UDSUBCLASS_HUB,	/* subclass */
3175 	.bDeviceProtocol = UDPROTO_SSHUB,	/* protocol */
3176 	.bMaxPacketSize = 9,			/* max packet size */
3177 	HSETW(.idVendor, 0x0000),		/* vendor */
3178 	HSETW(.idProduct, 0x0000),		/* product */
3179 	HSETW(.bcdDevice, 0x0100),		/* device version */
3180 	.iManufacturer = 1,
3181 	.iProduct = 2,
3182 	.iSerialNumber = 0,
3183 	.bNumConfigurations = 1,		/* # of configurations */
3184 };
3185 
3186 static const
3187 struct xhci_bos_desc xhci_bosd = {
3188 	.bosd = {
3189 		.bLength = sizeof(xhci_bosd.bosd),
3190 		.bDescriptorType = UDESC_BOS,
3191 		HSETW(.wTotalLength, sizeof(xhci_bosd)),
3192 		.bNumDeviceCaps = 3,
3193 	},
3194 	.usb2extd = {
3195 		.bLength = sizeof(xhci_bosd.usb2extd),
3196 		.bDescriptorType = 1,
3197 		.bDevCapabilityType = 2,
3198 		.bmAttributes[0] = 2,
3199 	},
3200 	.usbdcd = {
3201 		.bLength = sizeof(xhci_bosd.usbdcd),
3202 		.bDescriptorType = UDESC_DEVICE_CAPABILITY,
3203 		.bDevCapabilityType = 3,
3204 		.bmAttributes = 0, /* XXX */
3205 		HSETW(.wSpeedsSupported, 0x000C),
3206 		.bFunctionalitySupport = 8,
3207 		.bU1DevExitLat = 255,	/* dummy - not used */
3208 		.wU2DevExitLat = { 0x00, 0x08 },
3209 	},
3210 	.cidd = {
3211 		.bLength = sizeof(xhci_bosd.cidd),
3212 		.bDescriptorType = 1,
3213 		.bDevCapabilityType = 4,
3214 		.bReserved = 0,
3215 		.bContainerID = 0, /* XXX */
3216 	},
3217 };
3218 
3219 static const
3220 struct xhci_config_desc xhci_confd = {
3221 	.confd = {
3222 		.bLength = sizeof(xhci_confd.confd),
3223 		.bDescriptorType = UDESC_CONFIG,
3224 		.wTotalLength[0] = sizeof(xhci_confd),
3225 		.bNumInterface = 1,
3226 		.bConfigurationValue = 1,
3227 		.iConfiguration = 0,
3228 		.bmAttributes = UC_SELF_POWERED,
3229 		.bMaxPower = 0		/* max power */
3230 	},
3231 	.ifcd = {
3232 		.bLength = sizeof(xhci_confd.ifcd),
3233 		.bDescriptorType = UDESC_INTERFACE,
3234 		.bNumEndpoints = 1,
3235 		.bInterfaceClass = UICLASS_HUB,
3236 		.bInterfaceSubClass = UISUBCLASS_HUB,
3237 		.bInterfaceProtocol = 0,
3238 	},
3239 	.endpd = {
3240 		.bLength = sizeof(xhci_confd.endpd),
3241 		.bDescriptorType = UDESC_ENDPOINT,
3242 		.bEndpointAddress = UE_DIR_IN | XHCI_INTR_ENDPT,
3243 		.bmAttributes = UE_INTERRUPT,
3244 		.wMaxPacketSize[0] = 2,		/* max 15 ports */
3245 		.bInterval = 255,
3246 	},
3247 	.endpcd = {
3248 		.bLength = sizeof(xhci_confd.endpcd),
3249 		.bDescriptorType = UDESC_ENDPOINT_SS_COMP,
3250 		.bMaxBurst = 0,
3251 		.bmAttributes = 0,
3252 	},
3253 };
3254 
3255 static const
3256 struct usb_hub_ss_descriptor xhci_hubd = {
3257 	.bLength = sizeof(xhci_hubd),
3258 	.bDescriptorType = UDESC_SS_HUB,
3259 };
3260 
3261 static usb_error_t
3262 xhci_roothub_exec(struct usb_device *udev,
3263     struct usb_device_request *req, const void **pptr, uint16_t *plength)
3264 {
3265 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3266 	const char *str_ptr;
3267 	const void *ptr;
3268 	uint32_t port;
3269 	uint32_t v;
3270 	uint16_t len;
3271 	uint16_t i;
3272 	uint16_t value;
3273 	uint16_t index;
3274 	uint8_t j;
3275 	usb_error_t err;
3276 
3277 	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3278 
3279 	/* buffer reset */
3280 	ptr = (const void *)&sc->sc_hub_desc;
3281 	len = 0;
3282 	err = 0;
3283 
3284 	value = UGETW(req->wValue);
3285 	index = UGETW(req->wIndex);
3286 
3287 	DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
3288 	    "wValue=0x%04x wIndex=0x%04x\n",
3289 	    req->bmRequestType, req->bRequest,
3290 	    UGETW(req->wLength), value, index);
3291 
3292 #define	C(x,y) ((x) | ((y) << 8))
3293 	switch (C(req->bRequest, req->bmRequestType)) {
3294 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
3295 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
3296 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
3297 		/*
3298 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
3299 		 * for the integrated root hub.
3300 		 */
3301 		break;
3302 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
3303 		len = 1;
3304 		sc->sc_hub_desc.temp[0] = sc->sc_conf;
3305 		break;
3306 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3307 		switch (value >> 8) {
3308 		case UDESC_DEVICE:
3309 			if ((value & 0xff) != 0) {
3310 				err = USB_ERR_IOERROR;
3311 				goto done;
3312 			}
3313 			len = sizeof(xhci_devd);
3314 			ptr = (const void *)&xhci_devd;
3315 			break;
3316 
3317 		case UDESC_BOS:
3318 			if ((value & 0xff) != 0) {
3319 				err = USB_ERR_IOERROR;
3320 				goto done;
3321 			}
3322 			len = sizeof(xhci_bosd);
3323 			ptr = (const void *)&xhci_bosd;
3324 			break;
3325 
3326 		case UDESC_CONFIG:
3327 			if ((value & 0xff) != 0) {
3328 				err = USB_ERR_IOERROR;
3329 				goto done;
3330 			}
3331 			len = sizeof(xhci_confd);
3332 			ptr = (const void *)&xhci_confd;
3333 			break;
3334 
3335 		case UDESC_STRING:
3336 			switch (value & 0xff) {
3337 			case 0:	/* Language table */
3338 				str_ptr = "\001";
3339 				break;
3340 
3341 			case 1:	/* Vendor */
3342 				str_ptr = sc->sc_vendor;
3343 				break;
3344 
3345 			case 2:	/* Product */
3346 				str_ptr = "XHCI root HUB";
3347 				break;
3348 
3349 			default:
3350 				str_ptr = "";
3351 				break;
3352 			}
3353 
3354 			len = usb_make_str_desc(
3355 			    sc->sc_hub_desc.temp,
3356 			    sizeof(sc->sc_hub_desc.temp),
3357 			    str_ptr);
3358 			break;
3359 
3360 		default:
3361 			err = USB_ERR_IOERROR;
3362 			goto done;
3363 		}
3364 		break;
3365 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
3366 		len = 1;
3367 		sc->sc_hub_desc.temp[0] = 0;
3368 		break;
3369 	case C(UR_GET_STATUS, UT_READ_DEVICE):
3370 		len = 2;
3371 		USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
3372 		break;
3373 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
3374 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
3375 		len = 2;
3376 		USETW(sc->sc_hub_desc.stat.wStatus, 0);
3377 		break;
3378 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
3379 		if (value >= XHCI_MAX_DEVICES) {
3380 			err = USB_ERR_IOERROR;
3381 			goto done;
3382 		}
3383 		break;
3384 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
3385 		if (value != 0 && value != 1) {
3386 			err = USB_ERR_IOERROR;
3387 			goto done;
3388 		}
3389 		sc->sc_conf = value;
3390 		break;
3391 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
3392 		break;
3393 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
3394 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
3395 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
3396 		err = USB_ERR_IOERROR;
3397 		goto done;
3398 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
3399 		break;
3400 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
3401 		break;
3402 		/* Hub requests */
3403 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3404 		break;
3405 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
3406 		DPRINTFN(9, "UR_CLEAR_PORT_FEATURE\n");
3407 
3408 		if ((index < 1) ||
3409 		    (index > sc->sc_noport)) {
3410 			err = USB_ERR_IOERROR;
3411 			goto done;
3412 		}
3413 		port = XHCI_PORTSC(index);
3414 
3415 		v = XREAD4(sc, oper, port);
3416 		i = XHCI_PS_PLS_GET(v);
3417 		v &= ~XHCI_PS_CLEAR;
3418 
3419 		switch (value) {
3420 		case UHF_C_BH_PORT_RESET:
3421 			XWRITE4(sc, oper, port, v | XHCI_PS_WRC);
3422 			break;
3423 		case UHF_C_PORT_CONFIG_ERROR:
3424 			XWRITE4(sc, oper, port, v | XHCI_PS_CEC);
3425 			break;
3426 		case UHF_C_PORT_SUSPEND:
3427 		case UHF_C_PORT_LINK_STATE:
3428 			XWRITE4(sc, oper, port, v | XHCI_PS_PLC);
3429 			break;
3430 		case UHF_C_PORT_CONNECTION:
3431 			XWRITE4(sc, oper, port, v | XHCI_PS_CSC);
3432 			break;
3433 		case UHF_C_PORT_ENABLE:
3434 			XWRITE4(sc, oper, port, v | XHCI_PS_PEC);
3435 			break;
3436 		case UHF_C_PORT_OVER_CURRENT:
3437 			XWRITE4(sc, oper, port, v | XHCI_PS_OCC);
3438 			break;
3439 		case UHF_C_PORT_RESET:
3440 			XWRITE4(sc, oper, port, v | XHCI_PS_PRC);
3441 			break;
3442 		case UHF_PORT_ENABLE:
3443 			XWRITE4(sc, oper, port, v | XHCI_PS_PED);
3444 			break;
3445 		case UHF_PORT_POWER:
3446 			XWRITE4(sc, oper, port, v & ~XHCI_PS_PP);
3447 			break;
3448 		case UHF_PORT_INDICATOR:
3449 			XWRITE4(sc, oper, port, v & ~XHCI_PS_PIC_SET(3));
3450 			break;
3451 		case UHF_PORT_SUSPEND:
3452 
3453 			/* U3 -> U15 */
3454 			if (i == 3) {
3455 				XWRITE4(sc, oper, port, v |
3456 				    XHCI_PS_PLS_SET(0xF) | XHCI_PS_LWS);
3457 			}
3458 
3459 			/* wait 20ms for resume sequence to complete */
3460 			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
3461 
3462 			/* U0 */
3463 			XWRITE4(sc, oper, port, v |
3464 			    XHCI_PS_PLS_SET(0) | XHCI_PS_LWS);
3465 			break;
3466 		default:
3467 			err = USB_ERR_IOERROR;
3468 			goto done;
3469 		}
3470 		break;
3471 
3472 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3473 		if ((value & 0xff) != 0) {
3474 			err = USB_ERR_IOERROR;
3475 			goto done;
3476 		}
3477 
3478 		v = XREAD4(sc, capa, XHCI_HCSPARAMS0);
3479 
3480 		sc->sc_hub_desc.hubd = xhci_hubd;
3481 
3482 		sc->sc_hub_desc.hubd.bNbrPorts = sc->sc_noport;
3483 
3484 		if (XHCI_HCS0_PPC(v))
3485 			i = UHD_PWR_INDIVIDUAL;
3486 		else
3487 			i = UHD_PWR_GANGED;
3488 
3489 		if (XHCI_HCS0_PIND(v))
3490 			i |= UHD_PORT_IND;
3491 
3492 		i |= UHD_OC_INDIVIDUAL;
3493 
3494 		USETW(sc->sc_hub_desc.hubd.wHubCharacteristics, i);
3495 
3496 		/* see XHCI section 5.4.9: */
3497 		sc->sc_hub_desc.hubd.bPwrOn2PwrGood = 10;
3498 
3499 		for (j = 1; j <= sc->sc_noport; j++) {
3500 
3501 			v = XREAD4(sc, oper, XHCI_PORTSC(j));
3502 			if (v & XHCI_PS_DR) {
3503 				sc->sc_hub_desc.hubd.
3504 				    DeviceRemovable[j / 8] |= 1U << (j % 8);
3505 			}
3506 		}
3507 		len = sc->sc_hub_desc.hubd.bLength;
3508 		break;
3509 
3510 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3511 		len = 16;
3512 		memset(sc->sc_hub_desc.temp, 0, 16);
3513 		break;
3514 
3515 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
3516 		DPRINTFN(9, "UR_GET_STATUS i=%d\n", index);
3517 
3518 		if ((index < 1) ||
3519 		    (index > sc->sc_noport)) {
3520 			err = USB_ERR_IOERROR;
3521 			goto done;
3522 		}
3523 
3524 		v = XREAD4(sc, oper, XHCI_PORTSC(index));
3525 
3526 		DPRINTFN(9, "port status=0x%08x\n", v);
3527 
3528 		i = UPS_PORT_LINK_STATE_SET(XHCI_PS_PLS_GET(v));
3529 
3530 		switch (XHCI_PS_SPEED_GET(v)) {
3531 		case 3:
3532 			i |= UPS_HIGH_SPEED;
3533 			break;
3534 		case 2:
3535 			i |= UPS_LOW_SPEED;
3536 			break;
3537 		case 1:
3538 			/* FULL speed */
3539 			break;
3540 		default:
3541 			i |= UPS_OTHER_SPEED;
3542 			break;
3543 		}
3544 
3545 		if (v & XHCI_PS_CCS)
3546 			i |= UPS_CURRENT_CONNECT_STATUS;
3547 		if (v & XHCI_PS_PED)
3548 			i |= UPS_PORT_ENABLED;
3549 		if (v & XHCI_PS_OCA)
3550 			i |= UPS_OVERCURRENT_INDICATOR;
3551 		if (v & XHCI_PS_PR)
3552 			i |= UPS_RESET;
3553 		if (v & XHCI_PS_PP) {
3554 			/*
3555 			 * The USB 3.0 RH is using the
3556 			 * USB 2.0's power bit
3557 			 */
3558 			i |= UPS_PORT_POWER;
3559 		}
3560 		USETW(sc->sc_hub_desc.ps.wPortStatus, i);
3561 
3562 		i = 0;
3563 		if (v & XHCI_PS_CSC)
3564 			i |= UPS_C_CONNECT_STATUS;
3565 		if (v & XHCI_PS_PEC)
3566 			i |= UPS_C_PORT_ENABLED;
3567 		if (v & XHCI_PS_OCC)
3568 			i |= UPS_C_OVERCURRENT_INDICATOR;
3569 		if (v & XHCI_PS_WRC)
3570 			i |= UPS_C_BH_PORT_RESET;
3571 		if (v & XHCI_PS_PRC)
3572 			i |= UPS_C_PORT_RESET;
3573 		if (v & XHCI_PS_PLC)
3574 			i |= UPS_C_PORT_LINK_STATE;
3575 		if (v & XHCI_PS_CEC)
3576 			i |= UPS_C_PORT_CONFIG_ERROR;
3577 
3578 		USETW(sc->sc_hub_desc.ps.wPortChange, i);
3579 		len = sizeof(sc->sc_hub_desc.ps);
3580 		break;
3581 
3582 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3583 		err = USB_ERR_IOERROR;
3584 		goto done;
3585 
3586 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3587 		break;
3588 
3589 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
3590 
3591 		i = index >> 8;
3592 		index &= 0x00FF;
3593 
3594 		if ((index < 1) ||
3595 		    (index > sc->sc_noport)) {
3596 			err = USB_ERR_IOERROR;
3597 			goto done;
3598 		}
3599 
3600 		port = XHCI_PORTSC(index);
3601 		v = XREAD4(sc, oper, port) & ~XHCI_PS_CLEAR;
3602 
3603 		switch (value) {
3604 		case UHF_PORT_U1_TIMEOUT:
3605 			if (XHCI_PS_SPEED_GET(v) != 4) {
3606 				err = USB_ERR_IOERROR;
3607 				goto done;
3608 			}
3609 			port = XHCI_PORTPMSC(index);
3610 			v = XREAD4(sc, oper, port);
3611 			v &= ~XHCI_PM3_U1TO_SET(0xFF);
3612 			v |= XHCI_PM3_U1TO_SET(i);
3613 			XWRITE4(sc, oper, port, v);
3614 			break;
3615 		case UHF_PORT_U2_TIMEOUT:
3616 			if (XHCI_PS_SPEED_GET(v) != 4) {
3617 				err = USB_ERR_IOERROR;
3618 				goto done;
3619 			}
3620 			port = XHCI_PORTPMSC(index);
3621 			v = XREAD4(sc, oper, port);
3622 			v &= ~XHCI_PM3_U2TO_SET(0xFF);
3623 			v |= XHCI_PM3_U2TO_SET(i);
3624 			XWRITE4(sc, oper, port, v);
3625 			break;
3626 		case UHF_BH_PORT_RESET:
3627 			XWRITE4(sc, oper, port, v | XHCI_PS_WPR);
3628 			break;
3629 		case UHF_PORT_LINK_STATE:
3630 			XWRITE4(sc, oper, port, v |
3631 			    XHCI_PS_PLS_SET(i) | XHCI_PS_LWS);
3632 			/* 4ms settle time */
3633 			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250);
3634 			break;
3635 		case UHF_PORT_ENABLE:
3636 			DPRINTFN(3, "set port enable %d\n", index);
3637 			break;
3638 		case UHF_PORT_SUSPEND:
3639 			DPRINTFN(6, "suspend port %u (LPM=%u)\n", index, i);
3640 			j = XHCI_PS_SPEED_GET(v);
3641 			if ((j < 1) || (j > 3)) {
3642 				/* non-supported speed */
3643 				err = USB_ERR_IOERROR;
3644 				goto done;
3645 			}
3646 			XWRITE4(sc, oper, port, v |
3647 			    XHCI_PS_PLS_SET(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
3648 			break;
3649 		case UHF_PORT_RESET:
3650 			DPRINTFN(6, "reset port %d\n", index);
3651 			XWRITE4(sc, oper, port, v | XHCI_PS_PR);
3652 			break;
3653 		case UHF_PORT_POWER:
3654 			DPRINTFN(3, "set port power %d\n", index);
3655 			XWRITE4(sc, oper, port, v | XHCI_PS_PP);
3656 			break;
3657 		case UHF_PORT_TEST:
3658 			DPRINTFN(3, "set port test %d\n", index);
3659 			break;
3660 		case UHF_PORT_INDICATOR:
3661 			DPRINTFN(3, "set port indicator %d\n", index);
3662 
3663 			v &= ~XHCI_PS_PIC_SET(3);
3664 			v |= XHCI_PS_PIC_SET(1);
3665 
3666 			XWRITE4(sc, oper, port, v);
3667 			break;
3668 		default:
3669 			err = USB_ERR_IOERROR;
3670 			goto done;
3671 		}
3672 		break;
3673 
3674 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
3675 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
3676 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
3677 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
3678 		break;
3679 	default:
3680 		err = USB_ERR_IOERROR;
3681 		goto done;
3682 	}
3683 done:
3684 	*plength = len;
3685 	*pptr = ptr;
3686 	return (err);
3687 }
3688 
3689 static void
3690 xhci_xfer_setup(struct usb_setup_params *parm)
3691 {
3692 	struct usb_page_search page_info;
3693 	struct usb_page_cache *pc;
3694 	struct xhci_softc *sc;
3695 	struct usb_xfer *xfer;
3696 	void *last_obj;
3697 	uint32_t ntd;
3698 	uint32_t n;
3699 
3700 	sc = XHCI_BUS2SC(parm->udev->bus);
3701 	xfer = parm->curr_xfer;
3702 
3703 	/*
3704 	 * The proof for the "ntd" formula is illustrated like this:
3705 	 *
3706 	 * +------------------------------------+
3707 	 * |                                    |
3708 	 * |         |remainder ->              |
3709 	 * |   +-----+---+                      |
3710 	 * |   | xxx | x | frm 0                |
3711 	 * |   +-----+---++                     |
3712 	 * |   | xxx | xx | frm 1               |
3713 	 * |   +-----+----+                     |
3714 	 * |            ...                     |
3715 	 * +------------------------------------+
3716 	 *
3717 	 * "xxx" means a completely full USB transfer descriptor
3718 	 *
3719 	 * "x" and "xx" means a short USB packet
3720 	 *
3721 	 * For the remainder of an USB transfer modulo
3722 	 * "max_data_length" we need two USB transfer descriptors.
3723 	 * One to transfer the remaining data and one to finalise with
3724 	 * a zero length packet in case the "force_short_xfer" flag is
3725 	 * set. We only need two USB transfer descriptors in the case
3726 	 * where the transfer length of the first one is a factor of
3727 	 * "max_frame_size". The rest of the needed USB transfer
3728 	 * descriptors is given by the buffer size divided by the
3729 	 * maximum data payload.
3730 	 */
3731 	parm->hc_max_packet_size = 0x400;
3732 	parm->hc_max_packet_count = 16 * 3;
3733 	parm->hc_max_frame_size = XHCI_TD_PAYLOAD_MAX;
3734 
3735 	xfer->flags_int.bdma_enable = 1;
3736 
3737 	usbd_transfer_setup_sub(parm);
3738 
3739 	if (xfer->flags_int.isochronous_xfr) {
3740 		ntd = ((1 * xfer->nframes)
3741 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3742 	} else if (xfer->flags_int.control_xfr) {
3743 		ntd = ((2 * xfer->nframes) + 1	/* STATUS */
3744 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3745 	} else {
3746 		ntd = ((2 * xfer->nframes)
3747 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3748 	}
3749 
3750 alloc_dma_set:
3751 
3752 	if (parm->err)
3753 		return;
3754 
3755 	/*
3756 	 * Allocate queue heads and transfer descriptors
3757 	 */
3758 	last_obj = NULL;
3759 
3760 	if (usbd_transfer_setup_sub_malloc(
3761 	    parm, &pc, sizeof(struct xhci_td),
3762 	    XHCI_TD_ALIGN, ntd)) {
3763 		parm->err = USB_ERR_NOMEM;
3764 		return;
3765 	}
3766 	if (parm->buf) {
3767 		for (n = 0; n != ntd; n++) {
3768 			struct xhci_td *td;
3769 
3770 			usbd_get_page(pc + n, 0, &page_info);
3771 
3772 			td = page_info.buffer;
3773 
3774 			/* init TD */
3775 			td->td_self = page_info.physaddr;
3776 			td->obj_next = last_obj;
3777 			td->page_cache = pc + n;
3778 
3779 			last_obj = td;
3780 
3781 			usb_pc_cpu_flush(pc + n);
3782 		}
3783 	}
3784 	xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
3785 
3786 	if (!xfer->flags_int.curr_dma_set) {
3787 		xfer->flags_int.curr_dma_set = 1;
3788 		goto alloc_dma_set;
3789 	}
3790 }
3791 
3792 static usb_error_t
3793 xhci_configure_reset_endpoint(struct usb_xfer *xfer)
3794 {
3795 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3796 	struct usb_page_search buf_inp;
3797 	struct usb_device *udev;
3798 	struct xhci_endpoint_ext *pepext;
3799 	struct usb_endpoint_descriptor *edesc;
3800 	struct usb_page_cache *pcinp;
3801 	usb_error_t err;
3802 	usb_stream_t stream_id;
3803 	uint8_t index;
3804 	uint8_t epno;
3805 
3806 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3807 	    xfer->endpoint->edesc);
3808 
3809 	udev = xfer->xroot->udev;
3810 	index = udev->controller_slot_id;
3811 
3812 	pcinp = &sc->sc_hw.devs[index].input_pc;
3813 
3814 	usbd_get_page(pcinp, 0, &buf_inp);
3815 
3816 	edesc = xfer->endpoint->edesc;
3817 
3818 	epno = edesc->bEndpointAddress;
3819 	stream_id = xfer->stream_id;
3820 
3821 	if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
3822 		epno |= UE_DIR_IN;
3823 
3824 	epno = XHCI_EPNO2EPID(epno);
3825 
3826  	if (epno == 0)
3827 		return (USB_ERR_NO_PIPE);		/* invalid */
3828 
3829 	XHCI_CMD_LOCK(sc);
3830 
3831 	/* configure endpoint */
3832 
3833 	err = xhci_configure_endpoint_by_xfer(xfer);
3834 
3835 	if (err != 0) {
3836 		XHCI_CMD_UNLOCK(sc);
3837 		return (err);
3838 	}
3839 
3840 	/*
3841 	 * Get the endpoint into the stopped state according to the
3842 	 * endpoint context state diagram in the XHCI specification:
3843 	 */
3844 
3845 	err = xhci_cmd_stop_ep(sc, 0, epno, index);
3846 
3847 	if (err != 0)
3848 		DPRINTF("Could not stop endpoint %u\n", epno);
3849 
3850 	err = xhci_cmd_reset_ep(sc, 0, epno, index);
3851 
3852 	if (err != 0)
3853 		DPRINTF("Could not reset endpoint %u\n", epno);
3854 
3855 	err = xhci_cmd_set_tr_dequeue_ptr(sc,
3856 	    (pepext->physaddr + (stream_id * sizeof(struct xhci_trb) *
3857 	    XHCI_MAX_TRANSFERS)) | XHCI_EPCTX_2_DCS_SET(1),
3858 	    stream_id, epno, index);
3859 
3860 	if (err != 0)
3861 		DPRINTF("Could not set dequeue ptr for endpoint %u\n", epno);
3862 
3863 	/*
3864 	 * Get the endpoint into the running state according to the
3865 	 * endpoint context state diagram in the XHCI specification:
3866 	 */
3867 
3868 	xhci_configure_mask(udev, (1U << epno) | 1U, 0);
3869 
3870 	err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
3871 
3872 	if (err != 0)
3873 		DPRINTF("Could not configure endpoint %u\n", epno);
3874 
3875 	err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
3876 
3877 	if (err != 0)
3878 		DPRINTF("Could not configure endpoint %u\n", epno);
3879 
3880 	XHCI_CMD_UNLOCK(sc);
3881 
3882 	return (0);
3883 }
3884 
3885 static void
3886 xhci_xfer_unsetup(struct usb_xfer *xfer)
3887 {
3888 	return;
3889 }
3890 
3891 static void
3892 xhci_start_dma_delay(struct usb_xfer *xfer)
3893 {
3894 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3895 
3896 	/* put transfer on interrupt queue (again) */
3897 	usbd_transfer_enqueue(&sc->sc_bus.intr_q, xfer);
3898 
3899 	(void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
3900 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
3901 }
3902 
3903 static void
3904 xhci_configure_msg(struct usb_proc_msg *pm)
3905 {
3906 	struct xhci_softc *sc;
3907 	struct xhci_endpoint_ext *pepext;
3908 	struct usb_xfer *xfer;
3909 
3910 	sc = XHCI_BUS2SC(((struct usb_bus_msg *)pm)->bus);
3911 
3912 restart:
3913 	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3914 
3915 		pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3916 		    xfer->endpoint->edesc);
3917 
3918 		if ((pepext->trb_halted != 0) ||
3919 		    (pepext->trb_running == 0)) {
3920 
3921 			uint16_t i;
3922 
3923 			/* clear halted and running */
3924 			pepext->trb_halted = 0;
3925 			pepext->trb_running = 0;
3926 
3927 			/* nuke remaining buffered transfers */
3928 
3929 			for (i = 0; i != (XHCI_MAX_TRANSFERS *
3930 			    XHCI_MAX_STREAMS); i++) {
3931 				/*
3932 				 * NOTE: We need to use the timeout
3933 				 * error code here else existing
3934 				 * isochronous clients can get
3935 				 * confused:
3936 				 */
3937 				if (pepext->xfer[i] != NULL) {
3938 					xhci_device_done(pepext->xfer[i],
3939 					    USB_ERR_TIMEOUT);
3940 				}
3941 			}
3942 
3943 			/*
3944 			 * NOTE: The USB transfer cannot vanish in
3945 			 * this state!
3946 			 */
3947 
3948 			USB_BUS_UNLOCK(&sc->sc_bus);
3949 
3950 			xhci_configure_reset_endpoint(xfer);
3951 
3952 			USB_BUS_LOCK(&sc->sc_bus);
3953 
3954 			/* check if halted is still cleared */
3955 			if (pepext->trb_halted == 0) {
3956 				pepext->trb_running = 1;
3957 				memset(pepext->trb_index, 0,
3958 				    sizeof(pepext->trb_index));
3959 			}
3960 			goto restart;
3961 		}
3962 
3963 		if (xfer->flags_int.did_dma_delay) {
3964 
3965 			/* remove transfer from interrupt queue (again) */
3966 			usbd_transfer_dequeue(xfer);
3967 
3968 			/* we are finally done */
3969 			usb_dma_delay_done_cb(xfer);
3970 
3971 			/* queue changed - restart */
3972 			goto restart;
3973 		}
3974 	}
3975 
3976 	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3977 
3978 		/* try to insert xfer on HW queue */
3979 		xhci_transfer_insert(xfer);
3980 
3981 		/* try to multi buffer */
3982 		xhci_device_generic_multi_enter(xfer->endpoint,
3983 		    xfer->stream_id, NULL);
3984 	}
3985 }
3986 
3987 static void
3988 xhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
3989     struct usb_endpoint *ep)
3990 {
3991 	struct xhci_endpoint_ext *pepext;
3992 
3993 	DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n",
3994 	    ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode);
3995 
3996 	if (udev->parent_hub == NULL) {
3997 		/* root HUB has special endpoint handling */
3998 		return;
3999 	}
4000 
4001 	ep->methods = &xhci_device_generic_methods;
4002 
4003 	pepext = xhci_get_endpoint_ext(udev, edesc);
4004 
4005 	USB_BUS_LOCK(udev->bus);
4006 	pepext->trb_halted = 1;
4007 	pepext->trb_running = 0;
4008 	USB_BUS_UNLOCK(udev->bus);
4009 }
4010 
4011 static void
4012 xhci_ep_uninit(struct usb_device *udev, struct usb_endpoint *ep)
4013 {
4014 
4015 }
4016 
4017 static void
4018 xhci_ep_clear_stall(struct usb_device *udev, struct usb_endpoint *ep)
4019 {
4020 	struct xhci_endpoint_ext *pepext;
4021 
4022 	DPRINTF("\n");
4023 
4024 	if (udev->flags.usb_mode != USB_MODE_HOST) {
4025 		/* not supported */
4026 		return;
4027 	}
4028 	if (udev->parent_hub == NULL) {
4029 		/* root HUB has special endpoint handling */
4030 		return;
4031 	}
4032 
4033 	pepext = xhci_get_endpoint_ext(udev, ep->edesc);
4034 
4035 	USB_BUS_LOCK(udev->bus);
4036 	pepext->trb_halted = 1;
4037 	pepext->trb_running = 0;
4038 	USB_BUS_UNLOCK(udev->bus);
4039 }
4040 
4041 static usb_error_t
4042 xhci_device_init(struct usb_device *udev)
4043 {
4044 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4045 	usb_error_t err;
4046 	uint8_t temp;
4047 
4048 	/* no init for root HUB */
4049 	if (udev->parent_hub == NULL)
4050 		return (0);
4051 
4052 	XHCI_CMD_LOCK(sc);
4053 
4054 	/* set invalid default */
4055 
4056 	udev->controller_slot_id = sc->sc_noslot + 1;
4057 
4058 	/* try to get a new slot ID from the XHCI */
4059 
4060 	err = xhci_cmd_enable_slot(sc, &temp);
4061 
4062 	if (err) {
4063 		XHCI_CMD_UNLOCK(sc);
4064 		return (err);
4065 	}
4066 
4067 	if (temp > sc->sc_noslot) {
4068 		XHCI_CMD_UNLOCK(sc);
4069 		return (USB_ERR_BAD_ADDRESS);
4070 	}
4071 
4072 	if (sc->sc_hw.devs[temp].state != XHCI_ST_DISABLED) {
4073 		DPRINTF("slot %u already allocated.\n", temp);
4074 		XHCI_CMD_UNLOCK(sc);
4075 		return (USB_ERR_BAD_ADDRESS);
4076 	}
4077 
4078 	/* store slot ID for later reference */
4079 
4080 	udev->controller_slot_id = temp;
4081 
4082 	/* reset data structure */
4083 
4084 	memset(&sc->sc_hw.devs[temp], 0, sizeof(sc->sc_hw.devs[0]));
4085 
4086 	/* set mark slot allocated */
4087 
4088 	sc->sc_hw.devs[temp].state = XHCI_ST_ENABLED;
4089 
4090 	err = xhci_alloc_device_ext(udev);
4091 
4092 	XHCI_CMD_UNLOCK(sc);
4093 
4094 	/* get device into default state */
4095 
4096 	if (err == 0)
4097 		err = xhci_set_address(udev, NULL, 0);
4098 
4099 	return (err);
4100 }
4101 
4102 static void
4103 xhci_device_uninit(struct usb_device *udev)
4104 {
4105 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4106 	uint8_t index;
4107 
4108 	/* no init for root HUB */
4109 	if (udev->parent_hub == NULL)
4110 		return;
4111 
4112 	XHCI_CMD_LOCK(sc);
4113 
4114 	index = udev->controller_slot_id;
4115 
4116 	if (index <= sc->sc_noslot) {
4117 		xhci_cmd_disable_slot(sc, index);
4118 		sc->sc_hw.devs[index].state = XHCI_ST_DISABLED;
4119 
4120 		/* free device extension */
4121 		xhci_free_device_ext(udev);
4122 	}
4123 
4124 	XHCI_CMD_UNLOCK(sc);
4125 }
4126 
4127 static void
4128 xhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
4129 {
4130 	/*
4131 	 * Wait until the hardware has finished any possible use of
4132 	 * the transfer descriptor(s)
4133 	 */
4134 	*pus = 2048;			/* microseconds */
4135 }
4136 
4137 static void
4138 xhci_device_resume(struct usb_device *udev)
4139 {
4140 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4141 	uint8_t index;
4142 	uint8_t n;
4143 	uint8_t p;
4144 
4145 	DPRINTF("\n");
4146 
4147 	/* check for root HUB */
4148 	if (udev->parent_hub == NULL)
4149 		return;
4150 
4151 	index = udev->controller_slot_id;
4152 
4153 	XHCI_CMD_LOCK(sc);
4154 
4155 	/* blindly resume all endpoints */
4156 
4157 	USB_BUS_LOCK(udev->bus);
4158 
4159 	for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4160 		for (p = 0; p != XHCI_MAX_STREAMS; p++) {
4161 			XWRITE4(sc, door, XHCI_DOORBELL(index),
4162 			    n | XHCI_DB_SID_SET(p));
4163 		}
4164 	}
4165 
4166 	USB_BUS_UNLOCK(udev->bus);
4167 
4168 	XHCI_CMD_UNLOCK(sc);
4169 }
4170 
4171 static void
4172 xhci_device_suspend(struct usb_device *udev)
4173 {
4174 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4175 	uint8_t index;
4176 	uint8_t n;
4177 	usb_error_t err;
4178 
4179 	DPRINTF("\n");
4180 
4181 	/* check for root HUB */
4182 	if (udev->parent_hub == NULL)
4183 		return;
4184 
4185 	index = udev->controller_slot_id;
4186 
4187 	XHCI_CMD_LOCK(sc);
4188 
4189 	/* blindly suspend all endpoints */
4190 
4191 	for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4192 		err = xhci_cmd_stop_ep(sc, 1, n, index);
4193 		if (err != 0) {
4194 			DPRINTF("Failed to suspend endpoint "
4195 			    "%u on slot %u (ignored).\n", n, index);
4196 		}
4197 	}
4198 
4199 	XHCI_CMD_UNLOCK(sc);
4200 }
4201 
4202 static void
4203 xhci_set_hw_power(struct usb_bus *bus)
4204 {
4205 	DPRINTF("\n");
4206 }
4207 
4208 static void
4209 xhci_device_state_change(struct usb_device *udev)
4210 {
4211 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4212 	struct usb_page_search buf_inp;
4213 	usb_error_t err;
4214 	uint8_t index;
4215 
4216 	/* check for root HUB */
4217 	if (udev->parent_hub == NULL)
4218 		return;
4219 
4220 	index = udev->controller_slot_id;
4221 
4222 	DPRINTF("\n");
4223 
4224 	if (usb_get_device_state(udev) == USB_STATE_CONFIGURED) {
4225 		err = uhub_query_info(udev, &sc->sc_hw.devs[index].nports,
4226 		    &sc->sc_hw.devs[index].tt);
4227 		if (err != 0)
4228 			sc->sc_hw.devs[index].nports = 0;
4229 	}
4230 
4231 	XHCI_CMD_LOCK(sc);
4232 
4233 	switch (usb_get_device_state(udev)) {
4234 	case USB_STATE_POWERED:
4235 		if (sc->sc_hw.devs[index].state == XHCI_ST_DEFAULT)
4236 			break;
4237 
4238 		/* set default state */
4239 		sc->sc_hw.devs[index].state = XHCI_ST_DEFAULT;
4240 
4241 		/* reset number of contexts */
4242 		sc->sc_hw.devs[index].context_num = 0;
4243 
4244 		err = xhci_cmd_reset_dev(sc, index);
4245 
4246 		if (err != 0) {
4247 			DPRINTF("Device reset failed "
4248 			    "for slot %u.\n", index);
4249 		}
4250 		break;
4251 
4252 	case USB_STATE_ADDRESSED:
4253 		if (sc->sc_hw.devs[index].state == XHCI_ST_ADDRESSED)
4254 			break;
4255 
4256 		sc->sc_hw.devs[index].state = XHCI_ST_ADDRESSED;
4257 
4258 		err = xhci_cmd_configure_ep(sc, 0, 1, index);
4259 
4260 		if (err) {
4261 			DPRINTF("Failed to deconfigure "
4262 			    "slot %u.\n", index);
4263 		}
4264 		break;
4265 
4266 	case USB_STATE_CONFIGURED:
4267 		if (sc->sc_hw.devs[index].state == XHCI_ST_CONFIGURED)
4268 			break;
4269 
4270 		/* set configured state */
4271 		sc->sc_hw.devs[index].state = XHCI_ST_CONFIGURED;
4272 
4273 		/* reset number of contexts */
4274 		sc->sc_hw.devs[index].context_num = 0;
4275 
4276 		usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
4277 
4278 		xhci_configure_mask(udev, 3, 0);
4279 
4280 		err = xhci_configure_device(udev);
4281 		if (err != 0) {
4282 			DPRINTF("Could not configure device "
4283 			    "at slot %u.\n", index);
4284 		}
4285 
4286 		err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
4287 		if (err != 0) {
4288 			DPRINTF("Could not evaluate device "
4289 			    "context at slot %u.\n", index);
4290 		}
4291 		break;
4292 
4293 	default:
4294 		break;
4295 	}
4296 	XHCI_CMD_UNLOCK(sc);
4297 }
4298 
4299 static usb_error_t
4300 xhci_set_endpoint_mode(struct usb_device *udev, struct usb_endpoint *ep,
4301     uint8_t ep_mode)
4302 {
4303 	switch (ep_mode) {
4304 	case USB_EP_MODE_DEFAULT:
4305 		return (0);
4306 	case USB_EP_MODE_STREAMS:
4307 		if (xhcistreams == 0 ||
4308 		    (ep->edesc->bmAttributes & UE_XFERTYPE) != UE_BULK ||
4309 		    udev->speed != USB_SPEED_SUPER)
4310 			return (USB_ERR_INVAL);
4311 		return (0);
4312 	default:
4313 		return (USB_ERR_INVAL);
4314 	}
4315 }
4316 
4317 static const struct usb_bus_methods xhci_bus_methods = {
4318 	.endpoint_init = xhci_ep_init,
4319 	.endpoint_uninit = xhci_ep_uninit,
4320 	.xfer_setup = xhci_xfer_setup,
4321 	.xfer_unsetup = xhci_xfer_unsetup,
4322 	.get_dma_delay = xhci_get_dma_delay,
4323 	.device_init = xhci_device_init,
4324 	.device_uninit = xhci_device_uninit,
4325 	.device_resume = xhci_device_resume,
4326 	.device_suspend = xhci_device_suspend,
4327 	.set_hw_power = xhci_set_hw_power,
4328 	.roothub_exec = xhci_roothub_exec,
4329 	.xfer_poll = xhci_do_poll,
4330 	.start_dma_delay = xhci_start_dma_delay,
4331 	.set_address = xhci_set_address,
4332 	.clear_stall = xhci_ep_clear_stall,
4333 	.device_state_change = xhci_device_state_change,
4334 	.set_hw_power_sleep = xhci_set_hw_power_sleep,
4335 	.set_endpoint_mode = xhci_set_endpoint_mode,
4336 };
4337