xref: /freebsd/sys/dev/usb/controller/xhci.c (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
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 = (len_old - npkt_off + temp->max_packet_size - 1) /
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 = (temp.len + xfer->max_packet_size - 1) /
2189 			    xfer->max_packet_size;
2190 
2191 			temp.tbc = ((tdpc + mult - 1) / mult) - 1;
2192 			temp.tlbpc = (tdpc % mult);
2193 
2194 			if (temp.tlbpc == 0)
2195 				temp.tlbpc = mult - 1;
2196 			else
2197 				temp.tlbpc--;
2198 		} else {
2199 
2200 			/* regular data transfer */
2201 
2202 			temp.shortpkt = xfer->flags.force_short_xfer ? 0 : 1;
2203 		}
2204 
2205 		xhci_setup_generic_chain_sub(&temp);
2206 
2207 		if (xfer->flags_int.isochronous_xfr) {
2208 			temp.offset += xfer->frlengths[x - 1];
2209 			temp.isoc_frame += temp.isoc_delta;
2210 		} else {
2211 			/* get next Page Cache pointer */
2212 			temp.pc = xfer->frbuffers + x;
2213 		}
2214 	}
2215 
2216 	/* check if we should append a status stage */
2217 
2218 	if (xfer->flags_int.control_xfr &&
2219 	    !xfer->flags_int.control_act) {
2220 
2221 		/*
2222 		 * Send a DATA1 message and invert the current
2223 		 * endpoint direction.
2224 		 */
2225 		temp.step_td = (xfer->nframes != 0);
2226 		temp.direction = UE_GET_DIR(xfer->endpointno) ^ UE_DIR_IN;
2227 		temp.len = 0;
2228 		temp.pc = NULL;
2229 		temp.shortpkt = 0;
2230 		temp.last_frame = 1;
2231 		temp.trb_type = XHCI_TRB_TYPE_STATUS_STAGE;
2232 
2233 		xhci_setup_generic_chain_sub(&temp);
2234 	}
2235 
2236 	td = temp.td;
2237 
2238 	/* must have at least one frame! */
2239 
2240 	xfer->td_transfer_last = td;
2241 
2242 	DPRINTF("first=%p last=%p\n", xfer->td_transfer_first, td);
2243 }
2244 
2245 static void
2246 xhci_set_slot_pointer(struct xhci_softc *sc, uint8_t index, uint64_t dev_addr)
2247 {
2248 	struct usb_page_search buf_res;
2249 	struct xhci_dev_ctx_addr *pdctxa;
2250 
2251 	usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
2252 
2253 	pdctxa = buf_res.buffer;
2254 
2255 	DPRINTF("addr[%u]=0x%016llx\n", index, (long long)dev_addr);
2256 
2257 	pdctxa->qwBaaDevCtxAddr[index] = htole64(dev_addr);
2258 
2259 	usb_pc_cpu_flush(&sc->sc_hw.ctx_pc);
2260 }
2261 
2262 static usb_error_t
2263 xhci_configure_mask(struct usb_device *udev, uint32_t mask, uint8_t drop)
2264 {
2265 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2266 	struct usb_page_search buf_inp;
2267 	struct xhci_input_dev_ctx *pinp;
2268 	uint32_t temp;
2269 	uint8_t index;
2270 	uint8_t x;
2271 
2272 	index = udev->controller_slot_id;
2273 
2274 	usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2275 
2276 	pinp = buf_inp.buffer;
2277 
2278 	if (drop) {
2279 		mask &= XHCI_INCTX_NON_CTRL_MASK;
2280 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0, mask);
2281 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, 0);
2282 	} else {
2283 		/*
2284 		 * Some hardware requires that we drop the endpoint
2285 		 * context before adding it again:
2286 		 */
2287 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx0,
2288 		    mask & XHCI_INCTX_NON_CTRL_MASK);
2289 
2290 		/* Add new endpoint context */
2291 		xhci_ctx_set_le32(sc, &pinp->ctx_input.dwInCtx1, mask);
2292 
2293 		/* find most significant set bit */
2294 		for (x = 31; x != 1; x--) {
2295 			if (mask & (1 << x))
2296 				break;
2297 		}
2298 
2299 		/* adjust */
2300 		x--;
2301 
2302 		/* figure out the maximum number of contexts */
2303 		if (x > sc->sc_hw.devs[index].context_num)
2304 			sc->sc_hw.devs[index].context_num = x;
2305 		else
2306 			x = sc->sc_hw.devs[index].context_num;
2307 
2308 		/* update number of contexts */
2309 		temp = xhci_ctx_get_le32(sc, &pinp->ctx_slot.dwSctx0);
2310 		temp &= ~XHCI_SCTX_0_CTX_NUM_SET(31);
2311 		temp |= XHCI_SCTX_0_CTX_NUM_SET(x + 1);
2312 		xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2313 	}
2314 	usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2315 	return (0);
2316 }
2317 
2318 static usb_error_t
2319 xhci_configure_endpoint(struct usb_device *udev,
2320     struct usb_endpoint_descriptor *edesc, struct xhci_endpoint_ext *pepext,
2321     uint16_t interval, uint8_t max_packet_count,
2322     uint8_t mult, uint8_t fps_shift, uint16_t max_packet_size,
2323     uint16_t max_frame_size, uint8_t ep_mode)
2324 {
2325 	struct usb_page_search buf_inp;
2326 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2327 	struct xhci_input_dev_ctx *pinp;
2328 	uint64_t ring_addr = pepext->physaddr;
2329 	uint32_t temp;
2330 	uint8_t index;
2331 	uint8_t epno;
2332 	uint8_t type;
2333 
2334 	index = udev->controller_slot_id;
2335 
2336 	usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
2337 
2338 	pinp = buf_inp.buffer;
2339 
2340 	epno = edesc->bEndpointAddress;
2341 	type = edesc->bmAttributes & UE_XFERTYPE;
2342 
2343 	if (type == UE_CONTROL)
2344 		epno |= UE_DIR_IN;
2345 
2346 	epno = XHCI_EPNO2EPID(epno);
2347 
2348  	if (epno == 0)
2349 		return (USB_ERR_NO_PIPE);		/* invalid */
2350 
2351 	if (max_packet_count == 0)
2352 		return (USB_ERR_BAD_BUFSIZE);
2353 
2354 	max_packet_count--;
2355 
2356 	if (mult == 0)
2357 		return (USB_ERR_BAD_BUFSIZE);
2358 
2359 	/* store endpoint mode */
2360 	pepext->trb_ep_mode = ep_mode;
2361 	/* store bMaxPacketSize for control endpoints */
2362 	pepext->trb_ep_maxp = edesc->wMaxPacketSize[0];
2363 	usb_pc_cpu_flush(pepext->page_cache);
2364 
2365 	if (ep_mode == USB_EP_MODE_STREAMS) {
2366 		temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2367 		    XHCI_EPCTX_0_MAXP_STREAMS_SET(XHCI_MAX_STREAMS_LOG - 1) |
2368 		    XHCI_EPCTX_0_LSA_SET(1);
2369 
2370 		ring_addr += sizeof(struct xhci_trb) *
2371 		    XHCI_MAX_TRANSFERS * XHCI_MAX_STREAMS;
2372 	} else {
2373 		temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
2374 		    XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
2375 		    XHCI_EPCTX_0_LSA_SET(0);
2376 
2377 		ring_addr |= XHCI_EPCTX_2_DCS_SET(1);
2378 	}
2379 
2380 	switch (udev->speed) {
2381 	case USB_SPEED_FULL:
2382 	case USB_SPEED_LOW:
2383 		/* 1ms -> 125us */
2384 		fps_shift += 3;
2385 		break;
2386 	default:
2387 		break;
2388 	}
2389 
2390 	switch (type) {
2391 	case UE_INTERRUPT:
2392 		if (fps_shift > 3)
2393 			fps_shift--;
2394 		temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2395 		break;
2396 	case UE_ISOCHRONOUS:
2397 		temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
2398 
2399 		switch (udev->speed) {
2400 		case USB_SPEED_SUPER:
2401 			if (mult > 3)
2402 				mult = 3;
2403 			temp |= XHCI_EPCTX_0_MULT_SET(mult - 1);
2404 			max_packet_count /= mult;
2405 			break;
2406 		default:
2407 			break;
2408 		}
2409 		break;
2410 	default:
2411 		break;
2412 	}
2413 
2414 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx0, temp);
2415 
2416 	temp =
2417 	    XHCI_EPCTX_1_HID_SET(0) |
2418 	    XHCI_EPCTX_1_MAXB_SET(max_packet_count) |
2419 	    XHCI_EPCTX_1_MAXP_SIZE_SET(max_packet_size);
2420 
2421 	/*
2422 	 * Always enable the "three strikes and you are gone" feature
2423 	 * except for ISOCHRONOUS endpoints. This is suggested by
2424 	 * section 4.3.3 in the XHCI specification about device slot
2425 	 * initialisation.
2426 	 */
2427 	if (type != UE_ISOCHRONOUS)
2428 		temp |= XHCI_EPCTX_1_CERR_SET(3);
2429 
2430 	switch (type) {
2431 	case UE_CONTROL:
2432 		temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2433 		break;
2434 	case UE_ISOCHRONOUS:
2435 		temp |= XHCI_EPCTX_1_EPTYPE_SET(1);
2436 		break;
2437 	case UE_BULK:
2438 		temp |= XHCI_EPCTX_1_EPTYPE_SET(2);
2439 		break;
2440 	default:
2441 		temp |= XHCI_EPCTX_1_EPTYPE_SET(3);
2442 		break;
2443 	}
2444 
2445 	/* check for IN direction */
2446 	if (epno & 1)
2447 		temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
2448 
2449 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx1, temp);
2450 	xhci_ctx_set_le64(sc, &pinp->ctx_ep[epno - 1].qwEpCtx2, ring_addr);
2451 
2452 	switch (edesc->bmAttributes & UE_XFERTYPE) {
2453 	case UE_INTERRUPT:
2454 	case UE_ISOCHRONOUS:
2455 		temp = XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(max_frame_size) |
2456 		    XHCI_EPCTX_4_AVG_TRB_LEN_SET(MIN(XHCI_PAGE_SIZE,
2457 		    max_frame_size));
2458 		break;
2459 	case UE_CONTROL:
2460 		temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8);
2461 		break;
2462 	default:
2463 		temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(XHCI_PAGE_SIZE);
2464 		break;
2465 	}
2466 
2467 	xhci_ctx_set_le32(sc, &pinp->ctx_ep[epno - 1].dwEpCtx4, temp);
2468 
2469 #ifdef USB_DEBUG
2470 	xhci_dump_endpoint(sc, &pinp->ctx_ep[epno - 1]);
2471 #endif
2472 	usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
2473 
2474 	return (0);		/* success */
2475 }
2476 
2477 static usb_error_t
2478 xhci_configure_endpoint_by_xfer(struct usb_xfer *xfer)
2479 {
2480 	struct xhci_endpoint_ext *pepext;
2481 	struct usb_endpoint_ss_comp_descriptor *ecomp;
2482 	usb_stream_t x;
2483 
2484 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2485 	    xfer->endpoint->edesc);
2486 
2487 	ecomp = xfer->endpoint->ecomp;
2488 
2489 	for (x = 0; x != XHCI_MAX_STREAMS; x++) {
2490 		uint64_t temp;
2491 
2492 		/* halt any transfers */
2493 		pepext->trb[x * XHCI_MAX_TRANSFERS].dwTrb3 = 0;
2494 
2495 		/* compute start of TRB ring for stream "x" */
2496 		temp = pepext->physaddr +
2497 		    (x * XHCI_MAX_TRANSFERS * sizeof(struct xhci_trb)) +
2498 		    XHCI_SCTX_0_SCT_SEC_TR_RING;
2499 
2500 		/* make tree structure */
2501 		pepext->trb[(XHCI_MAX_TRANSFERS *
2502 		    XHCI_MAX_STREAMS) + x].qwTrb0 = htole64(temp);
2503 
2504 		/* reserved fields */
2505 		pepext->trb[(XHCI_MAX_TRANSFERS *
2506                     XHCI_MAX_STREAMS) + x].dwTrb2 = 0;
2507 		pepext->trb[(XHCI_MAX_TRANSFERS *
2508 		    XHCI_MAX_STREAMS) + x].dwTrb3 = 0;
2509 	}
2510 	usb_pc_cpu_flush(pepext->page_cache);
2511 
2512 	return (xhci_configure_endpoint(xfer->xroot->udev,
2513 	    xfer->endpoint->edesc, pepext,
2514 	    xfer->interval, xfer->max_packet_count,
2515 	    (ecomp != NULL) ? UE_GET_SS_ISO_MULT(ecomp->bmAttributes) + 1 : 1,
2516 	    usbd_xfer_get_fps_shift(xfer), xfer->max_packet_size,
2517 	    xfer->max_frame_size, xfer->endpoint->ep_mode));
2518 }
2519 
2520 static usb_error_t
2521 xhci_configure_device(struct usb_device *udev)
2522 {
2523 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2524 	struct usb_page_search buf_inp;
2525 	struct usb_page_cache *pcinp;
2526 	struct xhci_input_dev_ctx *pinp;
2527 	struct usb_device *hubdev;
2528 	uint32_t temp;
2529 	uint32_t route;
2530 	uint32_t rh_port;
2531 	uint8_t is_hub;
2532 	uint8_t index;
2533 	uint8_t depth;
2534 
2535 	index = udev->controller_slot_id;
2536 
2537 	DPRINTF("index=%u\n", index);
2538 
2539 	pcinp = &sc->sc_hw.devs[index].input_pc;
2540 
2541 	usbd_get_page(pcinp, 0, &buf_inp);
2542 
2543 	pinp = buf_inp.buffer;
2544 
2545 	rh_port = 0;
2546 	route = 0;
2547 
2548 	/* figure out route string and root HUB port number */
2549 
2550 	for (hubdev = udev; hubdev != NULL; hubdev = hubdev->parent_hub) {
2551 
2552 		if (hubdev->parent_hub == NULL)
2553 			break;
2554 
2555 		depth = hubdev->parent_hub->depth;
2556 
2557 		/*
2558 		 * NOTE: HS/FS/LS devices and the SS root HUB can have
2559 		 * more than 15 ports
2560 		 */
2561 
2562 		rh_port = hubdev->port_no;
2563 
2564 		if (depth == 0)
2565 			break;
2566 
2567 		if (rh_port > 15)
2568 			rh_port = 15;
2569 
2570 		if (depth < 6)
2571 			route |= rh_port << (4 * (depth - 1));
2572 	}
2573 
2574 	DPRINTF("Route=0x%08x\n", route);
2575 
2576 	temp = XHCI_SCTX_0_ROUTE_SET(route) |
2577 	    XHCI_SCTX_0_CTX_NUM_SET(
2578 	    sc->sc_hw.devs[index].context_num + 1);
2579 
2580 	switch (udev->speed) {
2581 	case USB_SPEED_LOW:
2582 		temp |= XHCI_SCTX_0_SPEED_SET(2);
2583 		if (udev->parent_hs_hub != NULL &&
2584 		    udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2585 		    UDPROTO_HSHUBMTT) {
2586 			DPRINTF("Device inherits MTT\n");
2587 			temp |= XHCI_SCTX_0_MTT_SET(1);
2588 		}
2589 		break;
2590 	case USB_SPEED_HIGH:
2591 		temp |= XHCI_SCTX_0_SPEED_SET(3);
2592 		if (sc->sc_hw.devs[index].nports != 0 &&
2593 		    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) {
2594 			DPRINTF("HUB supports MTT\n");
2595 			temp |= XHCI_SCTX_0_MTT_SET(1);
2596 		}
2597 		break;
2598 	case USB_SPEED_FULL:
2599 		temp |= XHCI_SCTX_0_SPEED_SET(1);
2600 		if (udev->parent_hs_hub != NULL &&
2601 		    udev->parent_hs_hub->ddesc.bDeviceProtocol ==
2602 		    UDPROTO_HSHUBMTT) {
2603 			DPRINTF("Device inherits MTT\n");
2604 			temp |= XHCI_SCTX_0_MTT_SET(1);
2605 		}
2606 		break;
2607 	default:
2608 		temp |= XHCI_SCTX_0_SPEED_SET(4);
2609 		break;
2610 	}
2611 
2612 	is_hub = sc->sc_hw.devs[index].nports != 0 &&
2613 	    (udev->speed == USB_SPEED_SUPER ||
2614 	    udev->speed == USB_SPEED_HIGH);
2615 
2616 	if (is_hub)
2617 		temp |= XHCI_SCTX_0_HUB_SET(1);
2618 
2619 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx0, temp);
2620 
2621 	temp = XHCI_SCTX_1_RH_PORT_SET(rh_port);
2622 
2623 	if (is_hub) {
2624 		temp |= XHCI_SCTX_1_NUM_PORTS_SET(
2625 		    sc->sc_hw.devs[index].nports);
2626 	}
2627 
2628 	switch (udev->speed) {
2629 	case USB_SPEED_SUPER:
2630 		switch (sc->sc_hw.devs[index].state) {
2631 		case XHCI_ST_ADDRESSED:
2632 		case XHCI_ST_CONFIGURED:
2633 			/* enable power save */
2634 			temp |= XHCI_SCTX_1_MAX_EL_SET(sc->sc_exit_lat_max);
2635 			break;
2636 		default:
2637 			/* disable power save */
2638 			break;
2639 		}
2640 		break;
2641 	default:
2642 		break;
2643 	}
2644 
2645 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx1, temp);
2646 
2647 	temp = XHCI_SCTX_2_IRQ_TARGET_SET(0);
2648 
2649 	if (is_hub) {
2650 		temp |= XHCI_SCTX_2_TT_THINK_TIME_SET(
2651 		    sc->sc_hw.devs[index].tt);
2652 	}
2653 
2654 	hubdev = udev->parent_hs_hub;
2655 
2656 	/* check if we should activate the transaction translator */
2657 	switch (udev->speed) {
2658 	case USB_SPEED_FULL:
2659 	case USB_SPEED_LOW:
2660 		if (hubdev != NULL) {
2661 			temp |= XHCI_SCTX_2_TT_HUB_SID_SET(
2662 			    hubdev->controller_slot_id);
2663 			temp |= XHCI_SCTX_2_TT_PORT_NUM_SET(
2664 			    udev->hs_port_no);
2665 		}
2666 		break;
2667 	default:
2668 		break;
2669 	}
2670 
2671 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx2, temp);
2672 
2673 	/*
2674 	 * These fields should be initialized to zero, according to
2675 	 * XHCI section 6.2.2 - slot context:
2676 	 */
2677 	temp = XHCI_SCTX_3_DEV_ADDR_SET(0) |
2678 	    XHCI_SCTX_3_SLOT_STATE_SET(0);
2679 
2680 	xhci_ctx_set_le32(sc, &pinp->ctx_slot.dwSctx3, temp);
2681 
2682 #ifdef USB_DEBUG
2683 	xhci_dump_device(sc, &pinp->ctx_slot);
2684 #endif
2685 	usb_pc_cpu_flush(pcinp);
2686 
2687 	return (0);		/* success */
2688 }
2689 
2690 static usb_error_t
2691 xhci_alloc_device_ext(struct usb_device *udev)
2692 {
2693 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2694 	struct usb_page_search buf_dev;
2695 	struct usb_page_search buf_ep;
2696 	struct xhci_trb *trb;
2697 	struct usb_page_cache *pc;
2698 	struct usb_page *pg;
2699 	uint64_t addr;
2700 	uint8_t index;
2701 	uint8_t i;
2702 
2703 	index = udev->controller_slot_id;
2704 
2705 	pc = &sc->sc_hw.devs[index].device_pc;
2706 	pg = &sc->sc_hw.devs[index].device_pg;
2707 
2708 	/* need to initialize the page cache */
2709 	pc->tag_parent = sc->sc_bus.dma_parent_tag;
2710 
2711 	if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2712 	    (2 * sizeof(struct xhci_dev_ctx)) :
2713 	    sizeof(struct xhci_dev_ctx), XHCI_PAGE_SIZE))
2714 		goto error;
2715 
2716 	usbd_get_page(pc, 0, &buf_dev);
2717 
2718 	pc = &sc->sc_hw.devs[index].input_pc;
2719 	pg = &sc->sc_hw.devs[index].input_pg;
2720 
2721 	/* need to initialize the page cache */
2722 	pc->tag_parent = sc->sc_bus.dma_parent_tag;
2723 
2724 	if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
2725 	    (2 * sizeof(struct xhci_input_dev_ctx)) :
2726 	    sizeof(struct xhci_input_dev_ctx), XHCI_PAGE_SIZE)) {
2727 		goto error;
2728 	}
2729 
2730 	/* initialize all endpoint LINK TRBs */
2731 
2732 	for (i = 0; i != XHCI_MAX_ENDPOINTS; i++) {
2733 
2734 		pc = &sc->sc_hw.devs[index].endpoint_pc[i];
2735 		pg = &sc->sc_hw.devs[index].endpoint_pg[i];
2736 
2737 		/* need to initialize the page cache */
2738 		pc->tag_parent = sc->sc_bus.dma_parent_tag;
2739 
2740 		if (usb_pc_alloc_mem(pc, pg,
2741 		    sizeof(struct xhci_dev_endpoint_trbs), XHCI_TRB_ALIGN)) {
2742 			goto error;
2743 		}
2744 
2745 		/* lookup endpoint TRB ring */
2746 		usbd_get_page(pc, 0, &buf_ep);
2747 
2748 		/* get TRB pointer */
2749 		trb = buf_ep.buffer;
2750 		trb += XHCI_MAX_TRANSFERS - 1;
2751 
2752 		/* get TRB start address */
2753 		addr = buf_ep.physaddr;
2754 
2755 		/* create LINK TRB */
2756 		trb->qwTrb0 = htole64(addr);
2757 		trb->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2758 		trb->dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2759 		    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2760 
2761 		usb_pc_cpu_flush(pc);
2762 	}
2763 
2764 	xhci_set_slot_pointer(sc, index, buf_dev.physaddr);
2765 
2766 	return (0);
2767 
2768 error:
2769 	xhci_free_device_ext(udev);
2770 
2771 	return (USB_ERR_NOMEM);
2772 }
2773 
2774 static void
2775 xhci_free_device_ext(struct usb_device *udev)
2776 {
2777 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2778 	uint8_t index;
2779 	uint8_t i;
2780 
2781 	index = udev->controller_slot_id;
2782 	xhci_set_slot_pointer(sc, index, 0);
2783 
2784 	usb_pc_free_mem(&sc->sc_hw.devs[index].device_pc);
2785 	usb_pc_free_mem(&sc->sc_hw.devs[index].input_pc);
2786 	for (i = 0; i != XHCI_MAX_ENDPOINTS; i++)
2787 		usb_pc_free_mem(&sc->sc_hw.devs[index].endpoint_pc[i]);
2788 }
2789 
2790 static struct xhci_endpoint_ext *
2791 xhci_get_endpoint_ext(struct usb_device *udev, struct usb_endpoint_descriptor *edesc)
2792 {
2793 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
2794 	struct xhci_endpoint_ext *pepext;
2795 	struct usb_page_cache *pc;
2796 	struct usb_page_search buf_ep;
2797 	uint8_t epno;
2798 	uint8_t index;
2799 
2800 	epno = edesc->bEndpointAddress;
2801 	if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
2802 		epno |= UE_DIR_IN;
2803 
2804 	epno = XHCI_EPNO2EPID(epno);
2805 
2806 	index = udev->controller_slot_id;
2807 
2808 	pc = &sc->sc_hw.devs[index].endpoint_pc[epno];
2809 
2810 	usbd_get_page(pc, 0, &buf_ep);
2811 
2812 	pepext = &sc->sc_hw.devs[index].endp[epno];
2813 	pepext->page_cache = pc;
2814 	pepext->trb = buf_ep.buffer;
2815 	pepext->physaddr = buf_ep.physaddr;
2816 
2817 	return (pepext);
2818 }
2819 
2820 static void
2821 xhci_endpoint_doorbell(struct usb_xfer *xfer)
2822 {
2823 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2824 	uint8_t epno;
2825 	uint8_t index;
2826 
2827 	epno = xfer->endpointno;
2828 	if (xfer->flags_int.control_xfr)
2829 		epno |= UE_DIR_IN;
2830 
2831 	epno = XHCI_EPNO2EPID(epno);
2832 	index = xfer->xroot->udev->controller_slot_id;
2833 
2834 	if (xfer->xroot->udev->flags.self_suspended == 0) {
2835 		XWRITE4(sc, door, XHCI_DOORBELL(index),
2836 		    epno | XHCI_DB_SID_SET(xfer->stream_id));
2837 	}
2838 }
2839 
2840 static void
2841 xhci_transfer_remove(struct usb_xfer *xfer, usb_error_t error)
2842 {
2843 	struct xhci_endpoint_ext *pepext;
2844 
2845 	if (xfer->flags_int.bandwidth_reclaimed) {
2846 		xfer->flags_int.bandwidth_reclaimed = 0;
2847 
2848 		pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2849 		    xfer->endpoint->edesc);
2850 
2851 		pepext->trb_used[xfer->stream_id]--;
2852 
2853 		pepext->xfer[xfer->qh_pos] = NULL;
2854 
2855 		if (error && pepext->trb_running != 0) {
2856 			pepext->trb_halted = 1;
2857 			pepext->trb_running = 0;
2858 		}
2859 	}
2860 }
2861 
2862 static usb_error_t
2863 xhci_transfer_insert(struct usb_xfer *xfer)
2864 {
2865 	struct xhci_td *td_first;
2866 	struct xhci_td *td_last;
2867 	struct xhci_trb *trb_link;
2868 	struct xhci_endpoint_ext *pepext;
2869 	uint64_t addr;
2870 	usb_stream_t id;
2871 	uint8_t i;
2872 	uint8_t inext;
2873 	uint8_t trb_limit;
2874 
2875 	DPRINTFN(8, "\n");
2876 
2877 	id = xfer->stream_id;
2878 
2879 	/* check if already inserted */
2880 	if (xfer->flags_int.bandwidth_reclaimed) {
2881 		DPRINTFN(8, "Already in schedule\n");
2882 		return (0);
2883 	}
2884 
2885 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
2886 	    xfer->endpoint->edesc);
2887 
2888 	td_first = xfer->td_transfer_first;
2889 	td_last = xfer->td_transfer_last;
2890 	addr = pepext->physaddr;
2891 
2892 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2893 	case UE_CONTROL:
2894 	case UE_INTERRUPT:
2895 		/* single buffered */
2896 		trb_limit = 1;
2897 		break;
2898 	default:
2899 		/* multi buffered */
2900 		trb_limit = (XHCI_MAX_TRANSFERS - 2);
2901 		break;
2902 	}
2903 
2904 	if (pepext->trb_used[id] >= trb_limit) {
2905 		DPRINTFN(8, "Too many TDs queued.\n");
2906 		return (USB_ERR_NOMEM);
2907 	}
2908 
2909 	/* check if bMaxPacketSize changed */
2910 	if (xfer->flags_int.control_xfr != 0 &&
2911 	    pepext->trb_ep_maxp != xfer->endpoint->edesc->wMaxPacketSize[0]) {
2912 
2913 		DPRINTFN(8, "Reconfigure control endpoint\n");
2914 
2915 		/* force driver to reconfigure endpoint */
2916 		pepext->trb_halted = 1;
2917 		pepext->trb_running = 0;
2918 	}
2919 
2920 	/* check for stopped condition, after putting transfer on interrupt queue */
2921 	if (pepext->trb_running == 0) {
2922 		struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
2923 
2924 		DPRINTFN(8, "Not running\n");
2925 
2926 		/* start configuration */
2927 		(void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
2928 		    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2929 		return (0);
2930 	}
2931 
2932 	pepext->trb_used[id]++;
2933 
2934 	/* get current TRB index */
2935 	i = pepext->trb_index[id];
2936 
2937 	/* get next TRB index */
2938 	inext = (i + 1);
2939 
2940 	/* the last entry of the ring is a hardcoded link TRB */
2941 	if (inext >= (XHCI_MAX_TRANSFERS - 1))
2942 		inext = 0;
2943 
2944 	/* store next TRB index, before stream ID offset is added */
2945 	pepext->trb_index[id] = inext;
2946 
2947 	/* offset for stream */
2948 	i += id * XHCI_MAX_TRANSFERS;
2949 	inext += id * XHCI_MAX_TRANSFERS;
2950 
2951 	/* compute terminating return address */
2952 	addr += (inext * sizeof(struct xhci_trb));
2953 
2954 	/* compute link TRB pointer */
2955 	trb_link = td_last->td_trb + td_last->ntrb;
2956 
2957 	/* update next pointer of last link TRB */
2958 	trb_link->qwTrb0 = htole64(addr);
2959 	trb_link->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2960 	trb_link->dwTrb3 = htole32(XHCI_TRB_3_IOC_BIT |
2961 	    XHCI_TRB_3_CYCLE_BIT |
2962 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2963 
2964 #ifdef USB_DEBUG
2965 	xhci_dump_trb(&td_last->td_trb[td_last->ntrb]);
2966 #endif
2967 	usb_pc_cpu_flush(td_last->page_cache);
2968 
2969 	/* write ahead chain end marker */
2970 
2971 	pepext->trb[inext].qwTrb0 = 0;
2972 	pepext->trb[inext].dwTrb2 = 0;
2973 	pepext->trb[inext].dwTrb3 = 0;
2974 
2975 	/* update next pointer of link TRB */
2976 
2977 	pepext->trb[i].qwTrb0 = htole64((uint64_t)td_first->td_self);
2978 	pepext->trb[i].dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
2979 
2980 #ifdef USB_DEBUG
2981 	xhci_dump_trb(&pepext->trb[i]);
2982 #endif
2983 	usb_pc_cpu_flush(pepext->page_cache);
2984 
2985 	/* toggle cycle bit which activates the transfer chain */
2986 
2987 	pepext->trb[i].dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
2988 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
2989 
2990 	usb_pc_cpu_flush(pepext->page_cache);
2991 
2992 	DPRINTF("qh_pos = %u\n", i);
2993 
2994 	pepext->xfer[i] = xfer;
2995 
2996 	xfer->qh_pos = i;
2997 
2998 	xfer->flags_int.bandwidth_reclaimed = 1;
2999 
3000 	xhci_endpoint_doorbell(xfer);
3001 
3002 	return (0);
3003 }
3004 
3005 static void
3006 xhci_root_intr(struct xhci_softc *sc)
3007 {
3008 	uint16_t i;
3009 
3010 	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3011 
3012 	/* clear any old interrupt data */
3013 	memset(sc->sc_hub_idata, 0, sizeof(sc->sc_hub_idata));
3014 
3015 	for (i = 1; i <= sc->sc_noport; i++) {
3016 		/* pick out CHANGE bits from the status register */
3017 		if (XREAD4(sc, oper, XHCI_PORTSC(i)) & (
3018 		    XHCI_PS_CSC | XHCI_PS_PEC |
3019 		    XHCI_PS_OCC | XHCI_PS_WRC |
3020 		    XHCI_PS_PRC | XHCI_PS_PLC |
3021 		    XHCI_PS_CEC)) {
3022 			sc->sc_hub_idata[i / 8] |= 1 << (i % 8);
3023 			DPRINTF("port %d changed\n", i);
3024 		}
3025 	}
3026 	uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
3027 	    sizeof(sc->sc_hub_idata));
3028 }
3029 
3030 /*------------------------------------------------------------------------*
3031  *	xhci_device_done - XHCI done handler
3032  *
3033  * NOTE: This function can be called two times in a row on
3034  * the same USB transfer. From close and from interrupt.
3035  *------------------------------------------------------------------------*/
3036 static void
3037 xhci_device_done(struct usb_xfer *xfer, usb_error_t error)
3038 {
3039 	DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
3040 	    xfer, xfer->endpoint, error);
3041 
3042 	/* remove transfer from HW queue */
3043 	xhci_transfer_remove(xfer, error);
3044 
3045 	/* dequeue transfer and start next transfer */
3046 	usbd_transfer_done(xfer, error);
3047 }
3048 
3049 /*------------------------------------------------------------------------*
3050  * XHCI data transfer support (generic type)
3051  *------------------------------------------------------------------------*/
3052 static void
3053 xhci_device_generic_open(struct usb_xfer *xfer)
3054 {
3055 	if (xfer->flags_int.isochronous_xfr) {
3056 		switch (xfer->xroot->udev->speed) {
3057 		case USB_SPEED_FULL:
3058 			break;
3059 		default:
3060 			usb_hs_bandwidth_alloc(xfer);
3061 			break;
3062 		}
3063 	}
3064 }
3065 
3066 static void
3067 xhci_device_generic_close(struct usb_xfer *xfer)
3068 {
3069 	DPRINTF("\n");
3070 
3071 	xhci_device_done(xfer, USB_ERR_CANCELLED);
3072 
3073 	if (xfer->flags_int.isochronous_xfr) {
3074 		switch (xfer->xroot->udev->speed) {
3075 		case USB_SPEED_FULL:
3076 			break;
3077 		default:
3078 			usb_hs_bandwidth_free(xfer);
3079 			break;
3080 		}
3081 	}
3082 }
3083 
3084 static void
3085 xhci_device_generic_multi_enter(struct usb_endpoint *ep,
3086     usb_stream_t stream_id, struct usb_xfer *enter_xfer)
3087 {
3088 	struct usb_xfer *xfer;
3089 
3090 	/* check if there is a current transfer */
3091 	xfer = ep->endpoint_q[stream_id].curr;
3092 	if (xfer == NULL)
3093 		return;
3094 
3095 	/*
3096 	 * Check if the current transfer is started and then pickup
3097 	 * the next one, if any. Else wait for next start event due to
3098 	 * block on failure feature.
3099 	 */
3100 	if (!xfer->flags_int.bandwidth_reclaimed)
3101 		return;
3102 
3103 	xfer = TAILQ_FIRST(&ep->endpoint_q[stream_id].head);
3104 	if (xfer == NULL) {
3105 		/*
3106 		 * In case of enter we have to consider that the
3107 		 * transfer is queued by the USB core after the enter
3108 		 * method is called.
3109 		 */
3110 		xfer = enter_xfer;
3111 
3112 		if (xfer == NULL)
3113 			return;
3114 	}
3115 
3116 	/* try to multi buffer */
3117 	xhci_transfer_insert(xfer);
3118 }
3119 
3120 static void
3121 xhci_device_generic_enter(struct usb_xfer *xfer)
3122 {
3123 	DPRINTF("\n");
3124 
3125 	/* set up TD's and QH */
3126 	xhci_setup_generic_chain(xfer);
3127 
3128 	xhci_device_generic_multi_enter(xfer->endpoint,
3129 	    xfer->stream_id, xfer);
3130 }
3131 
3132 static void
3133 xhci_device_generic_start(struct usb_xfer *xfer)
3134 {
3135 	DPRINTF("\n");
3136 
3137 	/* try to insert xfer on HW queue */
3138 	xhci_transfer_insert(xfer);
3139 
3140 	/* try to multi buffer */
3141 	xhci_device_generic_multi_enter(xfer->endpoint,
3142 	    xfer->stream_id, NULL);
3143 
3144 	/* add transfer last on interrupt queue */
3145 	usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
3146 
3147 	/* start timeout, if any */
3148 	if (xfer->timeout != 0)
3149 		usbd_transfer_timeout_ms(xfer, &xhci_timeout, xfer->timeout);
3150 }
3151 
3152 static const struct usb_pipe_methods xhci_device_generic_methods =
3153 {
3154 	.open = xhci_device_generic_open,
3155 	.close = xhci_device_generic_close,
3156 	.enter = xhci_device_generic_enter,
3157 	.start = xhci_device_generic_start,
3158 };
3159 
3160 /*------------------------------------------------------------------------*
3161  * xhci root HUB support
3162  *------------------------------------------------------------------------*
3163  * Simulate a hardware HUB by handling all the necessary requests.
3164  *------------------------------------------------------------------------*/
3165 
3166 #define	HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) }
3167 
3168 static const
3169 struct usb_device_descriptor xhci_devd =
3170 {
3171 	.bLength = sizeof(xhci_devd),
3172 	.bDescriptorType = UDESC_DEVICE,	/* type */
3173 	HSETW(.bcdUSB, 0x0300),			/* USB version */
3174 	.bDeviceClass = UDCLASS_HUB,		/* class */
3175 	.bDeviceSubClass = UDSUBCLASS_HUB,	/* subclass */
3176 	.bDeviceProtocol = UDPROTO_SSHUB,	/* protocol */
3177 	.bMaxPacketSize = 9,			/* max packet size */
3178 	HSETW(.idVendor, 0x0000),		/* vendor */
3179 	HSETW(.idProduct, 0x0000),		/* product */
3180 	HSETW(.bcdDevice, 0x0100),		/* device version */
3181 	.iManufacturer = 1,
3182 	.iProduct = 2,
3183 	.iSerialNumber = 0,
3184 	.bNumConfigurations = 1,		/* # of configurations */
3185 };
3186 
3187 static const
3188 struct xhci_bos_desc xhci_bosd = {
3189 	.bosd = {
3190 		.bLength = sizeof(xhci_bosd.bosd),
3191 		.bDescriptorType = UDESC_BOS,
3192 		HSETW(.wTotalLength, sizeof(xhci_bosd)),
3193 		.bNumDeviceCaps = 3,
3194 	},
3195 	.usb2extd = {
3196 		.bLength = sizeof(xhci_bosd.usb2extd),
3197 		.bDescriptorType = 1,
3198 		.bDevCapabilityType = 2,
3199 		.bmAttributes[0] = 2,
3200 	},
3201 	.usbdcd = {
3202 		.bLength = sizeof(xhci_bosd.usbdcd),
3203 		.bDescriptorType = UDESC_DEVICE_CAPABILITY,
3204 		.bDevCapabilityType = 3,
3205 		.bmAttributes = 0, /* XXX */
3206 		HSETW(.wSpeedsSupported, 0x000C),
3207 		.bFunctionalitySupport = 8,
3208 		.bU1DevExitLat = 255,	/* dummy - not used */
3209 		.wU2DevExitLat = { 0x00, 0x08 },
3210 	},
3211 	.cidd = {
3212 		.bLength = sizeof(xhci_bosd.cidd),
3213 		.bDescriptorType = 1,
3214 		.bDevCapabilityType = 4,
3215 		.bReserved = 0,
3216 		.bContainerID = 0, /* XXX */
3217 	},
3218 };
3219 
3220 static const
3221 struct xhci_config_desc xhci_confd = {
3222 	.confd = {
3223 		.bLength = sizeof(xhci_confd.confd),
3224 		.bDescriptorType = UDESC_CONFIG,
3225 		.wTotalLength[0] = sizeof(xhci_confd),
3226 		.bNumInterface = 1,
3227 		.bConfigurationValue = 1,
3228 		.iConfiguration = 0,
3229 		.bmAttributes = UC_SELF_POWERED,
3230 		.bMaxPower = 0		/* max power */
3231 	},
3232 	.ifcd = {
3233 		.bLength = sizeof(xhci_confd.ifcd),
3234 		.bDescriptorType = UDESC_INTERFACE,
3235 		.bNumEndpoints = 1,
3236 		.bInterfaceClass = UICLASS_HUB,
3237 		.bInterfaceSubClass = UISUBCLASS_HUB,
3238 		.bInterfaceProtocol = 0,
3239 	},
3240 	.endpd = {
3241 		.bLength = sizeof(xhci_confd.endpd),
3242 		.bDescriptorType = UDESC_ENDPOINT,
3243 		.bEndpointAddress = UE_DIR_IN | XHCI_INTR_ENDPT,
3244 		.bmAttributes = UE_INTERRUPT,
3245 		.wMaxPacketSize[0] = 2,		/* max 15 ports */
3246 		.bInterval = 255,
3247 	},
3248 	.endpcd = {
3249 		.bLength = sizeof(xhci_confd.endpcd),
3250 		.bDescriptorType = UDESC_ENDPOINT_SS_COMP,
3251 		.bMaxBurst = 0,
3252 		.bmAttributes = 0,
3253 	},
3254 };
3255 
3256 static const
3257 struct usb_hub_ss_descriptor xhci_hubd = {
3258 	.bLength = sizeof(xhci_hubd),
3259 	.bDescriptorType = UDESC_SS_HUB,
3260 };
3261 
3262 static usb_error_t
3263 xhci_roothub_exec(struct usb_device *udev,
3264     struct usb_device_request *req, const void **pptr, uint16_t *plength)
3265 {
3266 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
3267 	const char *str_ptr;
3268 	const void *ptr;
3269 	uint32_t port;
3270 	uint32_t v;
3271 	uint16_t len;
3272 	uint16_t i;
3273 	uint16_t value;
3274 	uint16_t index;
3275 	uint8_t j;
3276 	usb_error_t err;
3277 
3278 	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
3279 
3280 	/* buffer reset */
3281 	ptr = (const void *)&sc->sc_hub_desc;
3282 	len = 0;
3283 	err = 0;
3284 
3285 	value = UGETW(req->wValue);
3286 	index = UGETW(req->wIndex);
3287 
3288 	DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
3289 	    "wValue=0x%04x wIndex=0x%04x\n",
3290 	    req->bmRequestType, req->bRequest,
3291 	    UGETW(req->wLength), value, index);
3292 
3293 #define	C(x,y) ((x) | ((y) << 8))
3294 	switch (C(req->bRequest, req->bmRequestType)) {
3295 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
3296 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
3297 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
3298 		/*
3299 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
3300 		 * for the integrated root hub.
3301 		 */
3302 		break;
3303 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
3304 		len = 1;
3305 		sc->sc_hub_desc.temp[0] = sc->sc_conf;
3306 		break;
3307 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3308 		switch (value >> 8) {
3309 		case UDESC_DEVICE:
3310 			if ((value & 0xff) != 0) {
3311 				err = USB_ERR_IOERROR;
3312 				goto done;
3313 			}
3314 			len = sizeof(xhci_devd);
3315 			ptr = (const void *)&xhci_devd;
3316 			break;
3317 
3318 		case UDESC_BOS:
3319 			if ((value & 0xff) != 0) {
3320 				err = USB_ERR_IOERROR;
3321 				goto done;
3322 			}
3323 			len = sizeof(xhci_bosd);
3324 			ptr = (const void *)&xhci_bosd;
3325 			break;
3326 
3327 		case UDESC_CONFIG:
3328 			if ((value & 0xff) != 0) {
3329 				err = USB_ERR_IOERROR;
3330 				goto done;
3331 			}
3332 			len = sizeof(xhci_confd);
3333 			ptr = (const void *)&xhci_confd;
3334 			break;
3335 
3336 		case UDESC_STRING:
3337 			switch (value & 0xff) {
3338 			case 0:	/* Language table */
3339 				str_ptr = "\001";
3340 				break;
3341 
3342 			case 1:	/* Vendor */
3343 				str_ptr = sc->sc_vendor;
3344 				break;
3345 
3346 			case 2:	/* Product */
3347 				str_ptr = "XHCI root HUB";
3348 				break;
3349 
3350 			default:
3351 				str_ptr = "";
3352 				break;
3353 			}
3354 
3355 			len = usb_make_str_desc(
3356 			    sc->sc_hub_desc.temp,
3357 			    sizeof(sc->sc_hub_desc.temp),
3358 			    str_ptr);
3359 			break;
3360 
3361 		default:
3362 			err = USB_ERR_IOERROR;
3363 			goto done;
3364 		}
3365 		break;
3366 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
3367 		len = 1;
3368 		sc->sc_hub_desc.temp[0] = 0;
3369 		break;
3370 	case C(UR_GET_STATUS, UT_READ_DEVICE):
3371 		len = 2;
3372 		USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
3373 		break;
3374 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
3375 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
3376 		len = 2;
3377 		USETW(sc->sc_hub_desc.stat.wStatus, 0);
3378 		break;
3379 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
3380 		if (value >= XHCI_MAX_DEVICES) {
3381 			err = USB_ERR_IOERROR;
3382 			goto done;
3383 		}
3384 		break;
3385 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
3386 		if (value != 0 && value != 1) {
3387 			err = USB_ERR_IOERROR;
3388 			goto done;
3389 		}
3390 		sc->sc_conf = value;
3391 		break;
3392 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
3393 		break;
3394 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
3395 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
3396 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
3397 		err = USB_ERR_IOERROR;
3398 		goto done;
3399 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
3400 		break;
3401 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
3402 		break;
3403 		/* Hub requests */
3404 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3405 		break;
3406 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
3407 		DPRINTFN(9, "UR_CLEAR_PORT_FEATURE\n");
3408 
3409 		if ((index < 1) ||
3410 		    (index > sc->sc_noport)) {
3411 			err = USB_ERR_IOERROR;
3412 			goto done;
3413 		}
3414 		port = XHCI_PORTSC(index);
3415 
3416 		v = XREAD4(sc, oper, port);
3417 		i = XHCI_PS_PLS_GET(v);
3418 		v &= ~XHCI_PS_CLEAR;
3419 
3420 		switch (value) {
3421 		case UHF_C_BH_PORT_RESET:
3422 			XWRITE4(sc, oper, port, v | XHCI_PS_WRC);
3423 			break;
3424 		case UHF_C_PORT_CONFIG_ERROR:
3425 			XWRITE4(sc, oper, port, v | XHCI_PS_CEC);
3426 			break;
3427 		case UHF_C_PORT_SUSPEND:
3428 		case UHF_C_PORT_LINK_STATE:
3429 			XWRITE4(sc, oper, port, v | XHCI_PS_PLC);
3430 			break;
3431 		case UHF_C_PORT_CONNECTION:
3432 			XWRITE4(sc, oper, port, v | XHCI_PS_CSC);
3433 			break;
3434 		case UHF_C_PORT_ENABLE:
3435 			XWRITE4(sc, oper, port, v | XHCI_PS_PEC);
3436 			break;
3437 		case UHF_C_PORT_OVER_CURRENT:
3438 			XWRITE4(sc, oper, port, v | XHCI_PS_OCC);
3439 			break;
3440 		case UHF_C_PORT_RESET:
3441 			XWRITE4(sc, oper, port, v | XHCI_PS_PRC);
3442 			break;
3443 		case UHF_PORT_ENABLE:
3444 			XWRITE4(sc, oper, port, v | XHCI_PS_PED);
3445 			break;
3446 		case UHF_PORT_POWER:
3447 			XWRITE4(sc, oper, port, v & ~XHCI_PS_PP);
3448 			break;
3449 		case UHF_PORT_INDICATOR:
3450 			XWRITE4(sc, oper, port, v & ~XHCI_PS_PIC_SET(3));
3451 			break;
3452 		case UHF_PORT_SUSPEND:
3453 
3454 			/* U3 -> U15 */
3455 			if (i == 3) {
3456 				XWRITE4(sc, oper, port, v |
3457 				    XHCI_PS_PLS_SET(0xF) | XHCI_PS_LWS);
3458 			}
3459 
3460 			/* wait 20ms for resume sequence to complete */
3461 			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
3462 
3463 			/* U0 */
3464 			XWRITE4(sc, oper, port, v |
3465 			    XHCI_PS_PLS_SET(0) | XHCI_PS_LWS);
3466 			break;
3467 		default:
3468 			err = USB_ERR_IOERROR;
3469 			goto done;
3470 		}
3471 		break;
3472 
3473 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3474 		if ((value & 0xff) != 0) {
3475 			err = USB_ERR_IOERROR;
3476 			goto done;
3477 		}
3478 
3479 		v = XREAD4(sc, capa, XHCI_HCSPARAMS0);
3480 
3481 		sc->sc_hub_desc.hubd = xhci_hubd;
3482 
3483 		sc->sc_hub_desc.hubd.bNbrPorts = sc->sc_noport;
3484 
3485 		if (XHCI_HCS0_PPC(v))
3486 			i = UHD_PWR_INDIVIDUAL;
3487 		else
3488 			i = UHD_PWR_GANGED;
3489 
3490 		if (XHCI_HCS0_PIND(v))
3491 			i |= UHD_PORT_IND;
3492 
3493 		i |= UHD_OC_INDIVIDUAL;
3494 
3495 		USETW(sc->sc_hub_desc.hubd.wHubCharacteristics, i);
3496 
3497 		/* see XHCI section 5.4.9: */
3498 		sc->sc_hub_desc.hubd.bPwrOn2PwrGood = 10;
3499 
3500 		for (j = 1; j <= sc->sc_noport; j++) {
3501 
3502 			v = XREAD4(sc, oper, XHCI_PORTSC(j));
3503 			if (v & XHCI_PS_DR) {
3504 				sc->sc_hub_desc.hubd.
3505 				    DeviceRemovable[j / 8] |= 1U << (j % 8);
3506 			}
3507 		}
3508 		len = sc->sc_hub_desc.hubd.bLength;
3509 		break;
3510 
3511 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3512 		len = 16;
3513 		memset(sc->sc_hub_desc.temp, 0, 16);
3514 		break;
3515 
3516 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
3517 		DPRINTFN(9, "UR_GET_STATUS i=%d\n", index);
3518 
3519 		if ((index < 1) ||
3520 		    (index > sc->sc_noport)) {
3521 			err = USB_ERR_IOERROR;
3522 			goto done;
3523 		}
3524 
3525 		v = XREAD4(sc, oper, XHCI_PORTSC(index));
3526 
3527 		DPRINTFN(9, "port status=0x%08x\n", v);
3528 
3529 		i = UPS_PORT_LINK_STATE_SET(XHCI_PS_PLS_GET(v));
3530 
3531 		switch (XHCI_PS_SPEED_GET(v)) {
3532 		case 3:
3533 			i |= UPS_HIGH_SPEED;
3534 			break;
3535 		case 2:
3536 			i |= UPS_LOW_SPEED;
3537 			break;
3538 		case 1:
3539 			/* FULL speed */
3540 			break;
3541 		default:
3542 			i |= UPS_OTHER_SPEED;
3543 			break;
3544 		}
3545 
3546 		if (v & XHCI_PS_CCS)
3547 			i |= UPS_CURRENT_CONNECT_STATUS;
3548 		if (v & XHCI_PS_PED)
3549 			i |= UPS_PORT_ENABLED;
3550 		if (v & XHCI_PS_OCA)
3551 			i |= UPS_OVERCURRENT_INDICATOR;
3552 		if (v & XHCI_PS_PR)
3553 			i |= UPS_RESET;
3554 		if (v & XHCI_PS_PP) {
3555 			/*
3556 			 * The USB 3.0 RH is using the
3557 			 * USB 2.0's power bit
3558 			 */
3559 			i |= UPS_PORT_POWER;
3560 		}
3561 		USETW(sc->sc_hub_desc.ps.wPortStatus, i);
3562 
3563 		i = 0;
3564 		if (v & XHCI_PS_CSC)
3565 			i |= UPS_C_CONNECT_STATUS;
3566 		if (v & XHCI_PS_PEC)
3567 			i |= UPS_C_PORT_ENABLED;
3568 		if (v & XHCI_PS_OCC)
3569 			i |= UPS_C_OVERCURRENT_INDICATOR;
3570 		if (v & XHCI_PS_WRC)
3571 			i |= UPS_C_BH_PORT_RESET;
3572 		if (v & XHCI_PS_PRC)
3573 			i |= UPS_C_PORT_RESET;
3574 		if (v & XHCI_PS_PLC)
3575 			i |= UPS_C_PORT_LINK_STATE;
3576 		if (v & XHCI_PS_CEC)
3577 			i |= UPS_C_PORT_CONFIG_ERROR;
3578 
3579 		USETW(sc->sc_hub_desc.ps.wPortChange, i);
3580 		len = sizeof(sc->sc_hub_desc.ps);
3581 		break;
3582 
3583 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3584 		err = USB_ERR_IOERROR;
3585 		goto done;
3586 
3587 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3588 		break;
3589 
3590 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
3591 
3592 		i = index >> 8;
3593 		index &= 0x00FF;
3594 
3595 		if ((index < 1) ||
3596 		    (index > sc->sc_noport)) {
3597 			err = USB_ERR_IOERROR;
3598 			goto done;
3599 		}
3600 
3601 		port = XHCI_PORTSC(index);
3602 		v = XREAD4(sc, oper, port) & ~XHCI_PS_CLEAR;
3603 
3604 		switch (value) {
3605 		case UHF_PORT_U1_TIMEOUT:
3606 			if (XHCI_PS_SPEED_GET(v) != 4) {
3607 				err = USB_ERR_IOERROR;
3608 				goto done;
3609 			}
3610 			port = XHCI_PORTPMSC(index);
3611 			v = XREAD4(sc, oper, port);
3612 			v &= ~XHCI_PM3_U1TO_SET(0xFF);
3613 			v |= XHCI_PM3_U1TO_SET(i);
3614 			XWRITE4(sc, oper, port, v);
3615 			break;
3616 		case UHF_PORT_U2_TIMEOUT:
3617 			if (XHCI_PS_SPEED_GET(v) != 4) {
3618 				err = USB_ERR_IOERROR;
3619 				goto done;
3620 			}
3621 			port = XHCI_PORTPMSC(index);
3622 			v = XREAD4(sc, oper, port);
3623 			v &= ~XHCI_PM3_U2TO_SET(0xFF);
3624 			v |= XHCI_PM3_U2TO_SET(i);
3625 			XWRITE4(sc, oper, port, v);
3626 			break;
3627 		case UHF_BH_PORT_RESET:
3628 			XWRITE4(sc, oper, port, v | XHCI_PS_WPR);
3629 			break;
3630 		case UHF_PORT_LINK_STATE:
3631 			XWRITE4(sc, oper, port, v |
3632 			    XHCI_PS_PLS_SET(i) | XHCI_PS_LWS);
3633 			/* 4ms settle time */
3634 			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250);
3635 			break;
3636 		case UHF_PORT_ENABLE:
3637 			DPRINTFN(3, "set port enable %d\n", index);
3638 			break;
3639 		case UHF_PORT_SUSPEND:
3640 			DPRINTFN(6, "suspend port %u (LPM=%u)\n", index, i);
3641 			j = XHCI_PS_SPEED_GET(v);
3642 			if ((j < 1) || (j > 3)) {
3643 				/* non-supported speed */
3644 				err = USB_ERR_IOERROR;
3645 				goto done;
3646 			}
3647 			XWRITE4(sc, oper, port, v |
3648 			    XHCI_PS_PLS_SET(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
3649 			break;
3650 		case UHF_PORT_RESET:
3651 			DPRINTFN(6, "reset port %d\n", index);
3652 			XWRITE4(sc, oper, port, v | XHCI_PS_PR);
3653 			break;
3654 		case UHF_PORT_POWER:
3655 			DPRINTFN(3, "set port power %d\n", index);
3656 			XWRITE4(sc, oper, port, v | XHCI_PS_PP);
3657 			break;
3658 		case UHF_PORT_TEST:
3659 			DPRINTFN(3, "set port test %d\n", index);
3660 			break;
3661 		case UHF_PORT_INDICATOR:
3662 			DPRINTFN(3, "set port indicator %d\n", index);
3663 
3664 			v &= ~XHCI_PS_PIC_SET(3);
3665 			v |= XHCI_PS_PIC_SET(1);
3666 
3667 			XWRITE4(sc, oper, port, v);
3668 			break;
3669 		default:
3670 			err = USB_ERR_IOERROR;
3671 			goto done;
3672 		}
3673 		break;
3674 
3675 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
3676 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
3677 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
3678 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
3679 		break;
3680 	default:
3681 		err = USB_ERR_IOERROR;
3682 		goto done;
3683 	}
3684 done:
3685 	*plength = len;
3686 	*pptr = ptr;
3687 	return (err);
3688 }
3689 
3690 static void
3691 xhci_xfer_setup(struct usb_setup_params *parm)
3692 {
3693 	struct usb_page_search page_info;
3694 	struct usb_page_cache *pc;
3695 	struct xhci_softc *sc;
3696 	struct usb_xfer *xfer;
3697 	void *last_obj;
3698 	uint32_t ntd;
3699 	uint32_t n;
3700 
3701 	sc = XHCI_BUS2SC(parm->udev->bus);
3702 	xfer = parm->curr_xfer;
3703 
3704 	/*
3705 	 * The proof for the "ntd" formula is illustrated like this:
3706 	 *
3707 	 * +------------------------------------+
3708 	 * |                                    |
3709 	 * |         |remainder ->              |
3710 	 * |   +-----+---+                      |
3711 	 * |   | xxx | x | frm 0                |
3712 	 * |   +-----+---++                     |
3713 	 * |   | xxx | xx | frm 1               |
3714 	 * |   +-----+----+                     |
3715 	 * |            ...                     |
3716 	 * +------------------------------------+
3717 	 *
3718 	 * "xxx" means a completely full USB transfer descriptor
3719 	 *
3720 	 * "x" and "xx" means a short USB packet
3721 	 *
3722 	 * For the remainder of an USB transfer modulo
3723 	 * "max_data_length" we need two USB transfer descriptors.
3724 	 * One to transfer the remaining data and one to finalise with
3725 	 * a zero length packet in case the "force_short_xfer" flag is
3726 	 * set. We only need two USB transfer descriptors in the case
3727 	 * where the transfer length of the first one is a factor of
3728 	 * "max_frame_size". The rest of the needed USB transfer
3729 	 * descriptors is given by the buffer size divided by the
3730 	 * maximum data payload.
3731 	 */
3732 	parm->hc_max_packet_size = 0x400;
3733 	parm->hc_max_packet_count = 16 * 3;
3734 	parm->hc_max_frame_size = XHCI_TD_PAYLOAD_MAX;
3735 
3736 	xfer->flags_int.bdma_enable = 1;
3737 
3738 	usbd_transfer_setup_sub(parm);
3739 
3740 	if (xfer->flags_int.isochronous_xfr) {
3741 		ntd = ((1 * xfer->nframes)
3742 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3743 	} else if (xfer->flags_int.control_xfr) {
3744 		ntd = ((2 * xfer->nframes) + 1	/* STATUS */
3745 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3746 	} else {
3747 		ntd = ((2 * xfer->nframes)
3748 		    + (xfer->max_data_length / xfer->max_hc_frame_size));
3749 	}
3750 
3751 alloc_dma_set:
3752 
3753 	if (parm->err)
3754 		return;
3755 
3756 	/*
3757 	 * Allocate queue heads and transfer descriptors
3758 	 */
3759 	last_obj = NULL;
3760 
3761 	if (usbd_transfer_setup_sub_malloc(
3762 	    parm, &pc, sizeof(struct xhci_td),
3763 	    XHCI_TD_ALIGN, ntd)) {
3764 		parm->err = USB_ERR_NOMEM;
3765 		return;
3766 	}
3767 	if (parm->buf) {
3768 		for (n = 0; n != ntd; n++) {
3769 			struct xhci_td *td;
3770 
3771 			usbd_get_page(pc + n, 0, &page_info);
3772 
3773 			td = page_info.buffer;
3774 
3775 			/* init TD */
3776 			td->td_self = page_info.physaddr;
3777 			td->obj_next = last_obj;
3778 			td->page_cache = pc + n;
3779 
3780 			last_obj = td;
3781 
3782 			usb_pc_cpu_flush(pc + n);
3783 		}
3784 	}
3785 	xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
3786 
3787 	if (!xfer->flags_int.curr_dma_set) {
3788 		xfer->flags_int.curr_dma_set = 1;
3789 		goto alloc_dma_set;
3790 	}
3791 }
3792 
3793 static usb_error_t
3794 xhci_configure_reset_endpoint(struct usb_xfer *xfer)
3795 {
3796 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3797 	struct usb_page_search buf_inp;
3798 	struct usb_device *udev;
3799 	struct xhci_endpoint_ext *pepext;
3800 	struct usb_endpoint_descriptor *edesc;
3801 	struct usb_page_cache *pcinp;
3802 	usb_error_t err;
3803 	usb_stream_t stream_id;
3804 	uint8_t index;
3805 	uint8_t epno;
3806 
3807 	pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3808 	    xfer->endpoint->edesc);
3809 
3810 	udev = xfer->xroot->udev;
3811 	index = udev->controller_slot_id;
3812 
3813 	pcinp = &sc->sc_hw.devs[index].input_pc;
3814 
3815 	usbd_get_page(pcinp, 0, &buf_inp);
3816 
3817 	edesc = xfer->endpoint->edesc;
3818 
3819 	epno = edesc->bEndpointAddress;
3820 	stream_id = xfer->stream_id;
3821 
3822 	if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
3823 		epno |= UE_DIR_IN;
3824 
3825 	epno = XHCI_EPNO2EPID(epno);
3826 
3827  	if (epno == 0)
3828 		return (USB_ERR_NO_PIPE);		/* invalid */
3829 
3830 	XHCI_CMD_LOCK(sc);
3831 
3832 	/* configure endpoint */
3833 
3834 	err = xhci_configure_endpoint_by_xfer(xfer);
3835 
3836 	if (err != 0) {
3837 		XHCI_CMD_UNLOCK(sc);
3838 		return (err);
3839 	}
3840 
3841 	/*
3842 	 * Get the endpoint into the stopped state according to the
3843 	 * endpoint context state diagram in the XHCI specification:
3844 	 */
3845 
3846 	err = xhci_cmd_stop_ep(sc, 0, epno, index);
3847 
3848 	if (err != 0)
3849 		DPRINTF("Could not stop endpoint %u\n", epno);
3850 
3851 	err = xhci_cmd_reset_ep(sc, 0, epno, index);
3852 
3853 	if (err != 0)
3854 		DPRINTF("Could not reset endpoint %u\n", epno);
3855 
3856 	err = xhci_cmd_set_tr_dequeue_ptr(sc,
3857 	    (pepext->physaddr + (stream_id * sizeof(struct xhci_trb) *
3858 	    XHCI_MAX_TRANSFERS)) | XHCI_EPCTX_2_DCS_SET(1),
3859 	    stream_id, epno, index);
3860 
3861 	if (err != 0)
3862 		DPRINTF("Could not set dequeue ptr for endpoint %u\n", epno);
3863 
3864 	/*
3865 	 * Get the endpoint into the running state according to the
3866 	 * endpoint context state diagram in the XHCI specification:
3867 	 */
3868 
3869 	xhci_configure_mask(udev, (1U << epno) | 1U, 0);
3870 
3871 	err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
3872 
3873 	if (err != 0)
3874 		DPRINTF("Could not configure endpoint %u\n", epno);
3875 
3876 	err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
3877 
3878 	if (err != 0)
3879 		DPRINTF("Could not configure endpoint %u\n", epno);
3880 
3881 	XHCI_CMD_UNLOCK(sc);
3882 
3883 	return (0);
3884 }
3885 
3886 static void
3887 xhci_xfer_unsetup(struct usb_xfer *xfer)
3888 {
3889 	return;
3890 }
3891 
3892 static void
3893 xhci_start_dma_delay(struct usb_xfer *xfer)
3894 {
3895 	struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
3896 
3897 	/* put transfer on interrupt queue (again) */
3898 	usbd_transfer_enqueue(&sc->sc_bus.intr_q, xfer);
3899 
3900 	(void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
3901 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
3902 }
3903 
3904 static void
3905 xhci_configure_msg(struct usb_proc_msg *pm)
3906 {
3907 	struct xhci_softc *sc;
3908 	struct xhci_endpoint_ext *pepext;
3909 	struct usb_xfer *xfer;
3910 
3911 	sc = XHCI_BUS2SC(((struct usb_bus_msg *)pm)->bus);
3912 
3913 restart:
3914 	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3915 
3916 		pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
3917 		    xfer->endpoint->edesc);
3918 
3919 		if ((pepext->trb_halted != 0) ||
3920 		    (pepext->trb_running == 0)) {
3921 
3922 			uint16_t i;
3923 
3924 			/* clear halted and running */
3925 			pepext->trb_halted = 0;
3926 			pepext->trb_running = 0;
3927 
3928 			/* nuke remaining buffered transfers */
3929 
3930 			for (i = 0; i != (XHCI_MAX_TRANSFERS *
3931 			    XHCI_MAX_STREAMS); i++) {
3932 				/*
3933 				 * NOTE: We need to use the timeout
3934 				 * error code here else existing
3935 				 * isochronous clients can get
3936 				 * confused:
3937 				 */
3938 				if (pepext->xfer[i] != NULL) {
3939 					xhci_device_done(pepext->xfer[i],
3940 					    USB_ERR_TIMEOUT);
3941 				}
3942 			}
3943 
3944 			/*
3945 			 * NOTE: The USB transfer cannot vanish in
3946 			 * this state!
3947 			 */
3948 
3949 			USB_BUS_UNLOCK(&sc->sc_bus);
3950 
3951 			xhci_configure_reset_endpoint(xfer);
3952 
3953 			USB_BUS_LOCK(&sc->sc_bus);
3954 
3955 			/* check if halted is still cleared */
3956 			if (pepext->trb_halted == 0) {
3957 				pepext->trb_running = 1;
3958 				memset(pepext->trb_index, 0,
3959 				    sizeof(pepext->trb_index));
3960 			}
3961 			goto restart;
3962 		}
3963 
3964 		if (xfer->flags_int.did_dma_delay) {
3965 
3966 			/* remove transfer from interrupt queue (again) */
3967 			usbd_transfer_dequeue(xfer);
3968 
3969 			/* we are finally done */
3970 			usb_dma_delay_done_cb(xfer);
3971 
3972 			/* queue changed - restart */
3973 			goto restart;
3974 		}
3975 	}
3976 
3977 	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3978 
3979 		/* try to insert xfer on HW queue */
3980 		xhci_transfer_insert(xfer);
3981 
3982 		/* try to multi buffer */
3983 		xhci_device_generic_multi_enter(xfer->endpoint,
3984 		    xfer->stream_id, NULL);
3985 	}
3986 }
3987 
3988 static void
3989 xhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
3990     struct usb_endpoint *ep)
3991 {
3992 	struct xhci_endpoint_ext *pepext;
3993 
3994 	DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n",
3995 	    ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode);
3996 
3997 	if (udev->parent_hub == NULL) {
3998 		/* root HUB has special endpoint handling */
3999 		return;
4000 	}
4001 
4002 	ep->methods = &xhci_device_generic_methods;
4003 
4004 	pepext = xhci_get_endpoint_ext(udev, edesc);
4005 
4006 	USB_BUS_LOCK(udev->bus);
4007 	pepext->trb_halted = 1;
4008 	pepext->trb_running = 0;
4009 	USB_BUS_UNLOCK(udev->bus);
4010 }
4011 
4012 static void
4013 xhci_ep_uninit(struct usb_device *udev, struct usb_endpoint *ep)
4014 {
4015 
4016 }
4017 
4018 static void
4019 xhci_ep_clear_stall(struct usb_device *udev, struct usb_endpoint *ep)
4020 {
4021 	struct xhci_endpoint_ext *pepext;
4022 
4023 	DPRINTF("\n");
4024 
4025 	if (udev->flags.usb_mode != USB_MODE_HOST) {
4026 		/* not supported */
4027 		return;
4028 	}
4029 	if (udev->parent_hub == NULL) {
4030 		/* root HUB has special endpoint handling */
4031 		return;
4032 	}
4033 
4034 	pepext = xhci_get_endpoint_ext(udev, ep->edesc);
4035 
4036 	USB_BUS_LOCK(udev->bus);
4037 	pepext->trb_halted = 1;
4038 	pepext->trb_running = 0;
4039 	USB_BUS_UNLOCK(udev->bus);
4040 }
4041 
4042 static usb_error_t
4043 xhci_device_init(struct usb_device *udev)
4044 {
4045 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4046 	usb_error_t err;
4047 	uint8_t temp;
4048 
4049 	/* no init for root HUB */
4050 	if (udev->parent_hub == NULL)
4051 		return (0);
4052 
4053 	XHCI_CMD_LOCK(sc);
4054 
4055 	/* set invalid default */
4056 
4057 	udev->controller_slot_id = sc->sc_noslot + 1;
4058 
4059 	/* try to get a new slot ID from the XHCI */
4060 
4061 	err = xhci_cmd_enable_slot(sc, &temp);
4062 
4063 	if (err) {
4064 		XHCI_CMD_UNLOCK(sc);
4065 		return (err);
4066 	}
4067 
4068 	if (temp > sc->sc_noslot) {
4069 		XHCI_CMD_UNLOCK(sc);
4070 		return (USB_ERR_BAD_ADDRESS);
4071 	}
4072 
4073 	if (sc->sc_hw.devs[temp].state != XHCI_ST_DISABLED) {
4074 		DPRINTF("slot %u already allocated.\n", temp);
4075 		XHCI_CMD_UNLOCK(sc);
4076 		return (USB_ERR_BAD_ADDRESS);
4077 	}
4078 
4079 	/* store slot ID for later reference */
4080 
4081 	udev->controller_slot_id = temp;
4082 
4083 	/* reset data structure */
4084 
4085 	memset(&sc->sc_hw.devs[temp], 0, sizeof(sc->sc_hw.devs[0]));
4086 
4087 	/* set mark slot allocated */
4088 
4089 	sc->sc_hw.devs[temp].state = XHCI_ST_ENABLED;
4090 
4091 	err = xhci_alloc_device_ext(udev);
4092 
4093 	XHCI_CMD_UNLOCK(sc);
4094 
4095 	/* get device into default state */
4096 
4097 	if (err == 0)
4098 		err = xhci_set_address(udev, NULL, 0);
4099 
4100 	return (err);
4101 }
4102 
4103 static void
4104 xhci_device_uninit(struct usb_device *udev)
4105 {
4106 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4107 	uint8_t index;
4108 
4109 	/* no init for root HUB */
4110 	if (udev->parent_hub == NULL)
4111 		return;
4112 
4113 	XHCI_CMD_LOCK(sc);
4114 
4115 	index = udev->controller_slot_id;
4116 
4117 	if (index <= sc->sc_noslot) {
4118 		xhci_cmd_disable_slot(sc, index);
4119 		sc->sc_hw.devs[index].state = XHCI_ST_DISABLED;
4120 
4121 		/* free device extension */
4122 		xhci_free_device_ext(udev);
4123 	}
4124 
4125 	XHCI_CMD_UNLOCK(sc);
4126 }
4127 
4128 static void
4129 xhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
4130 {
4131 	/*
4132 	 * Wait until the hardware has finished any possible use of
4133 	 * the transfer descriptor(s)
4134 	 */
4135 	*pus = 2048;			/* microseconds */
4136 }
4137 
4138 static void
4139 xhci_device_resume(struct usb_device *udev)
4140 {
4141 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4142 	uint8_t index;
4143 	uint8_t n;
4144 	uint8_t p;
4145 
4146 	DPRINTF("\n");
4147 
4148 	/* check for root HUB */
4149 	if (udev->parent_hub == NULL)
4150 		return;
4151 
4152 	index = udev->controller_slot_id;
4153 
4154 	XHCI_CMD_LOCK(sc);
4155 
4156 	/* blindly resume all endpoints */
4157 
4158 	USB_BUS_LOCK(udev->bus);
4159 
4160 	for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4161 		for (p = 0; p != XHCI_MAX_STREAMS; p++) {
4162 			XWRITE4(sc, door, XHCI_DOORBELL(index),
4163 			    n | XHCI_DB_SID_SET(p));
4164 		}
4165 	}
4166 
4167 	USB_BUS_UNLOCK(udev->bus);
4168 
4169 	XHCI_CMD_UNLOCK(sc);
4170 }
4171 
4172 static void
4173 xhci_device_suspend(struct usb_device *udev)
4174 {
4175 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4176 	uint8_t index;
4177 	uint8_t n;
4178 	usb_error_t err;
4179 
4180 	DPRINTF("\n");
4181 
4182 	/* check for root HUB */
4183 	if (udev->parent_hub == NULL)
4184 		return;
4185 
4186 	index = udev->controller_slot_id;
4187 
4188 	XHCI_CMD_LOCK(sc);
4189 
4190 	/* blindly suspend all endpoints */
4191 
4192 	for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
4193 		err = xhci_cmd_stop_ep(sc, 1, n, index);
4194 		if (err != 0) {
4195 			DPRINTF("Failed to suspend endpoint "
4196 			    "%u on slot %u (ignored).\n", n, index);
4197 		}
4198 	}
4199 
4200 	XHCI_CMD_UNLOCK(sc);
4201 }
4202 
4203 static void
4204 xhci_set_hw_power(struct usb_bus *bus)
4205 {
4206 	DPRINTF("\n");
4207 }
4208 
4209 static void
4210 xhci_device_state_change(struct usb_device *udev)
4211 {
4212 	struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
4213 	struct usb_page_search buf_inp;
4214 	usb_error_t err;
4215 	uint8_t index;
4216 
4217 	/* check for root HUB */
4218 	if (udev->parent_hub == NULL)
4219 		return;
4220 
4221 	index = udev->controller_slot_id;
4222 
4223 	DPRINTF("\n");
4224 
4225 	if (usb_get_device_state(udev) == USB_STATE_CONFIGURED) {
4226 		err = uhub_query_info(udev, &sc->sc_hw.devs[index].nports,
4227 		    &sc->sc_hw.devs[index].tt);
4228 		if (err != 0)
4229 			sc->sc_hw.devs[index].nports = 0;
4230 	}
4231 
4232 	XHCI_CMD_LOCK(sc);
4233 
4234 	switch (usb_get_device_state(udev)) {
4235 	case USB_STATE_POWERED:
4236 		if (sc->sc_hw.devs[index].state == XHCI_ST_DEFAULT)
4237 			break;
4238 
4239 		/* set default state */
4240 		sc->sc_hw.devs[index].state = XHCI_ST_DEFAULT;
4241 
4242 		/* reset number of contexts */
4243 		sc->sc_hw.devs[index].context_num = 0;
4244 
4245 		err = xhci_cmd_reset_dev(sc, index);
4246 
4247 		if (err != 0) {
4248 			DPRINTF("Device reset failed "
4249 			    "for slot %u.\n", index);
4250 		}
4251 		break;
4252 
4253 	case USB_STATE_ADDRESSED:
4254 		if (sc->sc_hw.devs[index].state == XHCI_ST_ADDRESSED)
4255 			break;
4256 
4257 		sc->sc_hw.devs[index].state = XHCI_ST_ADDRESSED;
4258 
4259 		err = xhci_cmd_configure_ep(sc, 0, 1, index);
4260 
4261 		if (err) {
4262 			DPRINTF("Failed to deconfigure "
4263 			    "slot %u.\n", index);
4264 		}
4265 		break;
4266 
4267 	case USB_STATE_CONFIGURED:
4268 		if (sc->sc_hw.devs[index].state == XHCI_ST_CONFIGURED)
4269 			break;
4270 
4271 		/* set configured state */
4272 		sc->sc_hw.devs[index].state = XHCI_ST_CONFIGURED;
4273 
4274 		/* reset number of contexts */
4275 		sc->sc_hw.devs[index].context_num = 0;
4276 
4277 		usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
4278 
4279 		xhci_configure_mask(udev, 3, 0);
4280 
4281 		err = xhci_configure_device(udev);
4282 		if (err != 0) {
4283 			DPRINTF("Could not configure device "
4284 			    "at slot %u.\n", index);
4285 		}
4286 
4287 		err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
4288 		if (err != 0) {
4289 			DPRINTF("Could not evaluate device "
4290 			    "context at slot %u.\n", index);
4291 		}
4292 		break;
4293 
4294 	default:
4295 		break;
4296 	}
4297 	XHCI_CMD_UNLOCK(sc);
4298 }
4299 
4300 static usb_error_t
4301 xhci_set_endpoint_mode(struct usb_device *udev, struct usb_endpoint *ep,
4302     uint8_t ep_mode)
4303 {
4304 	switch (ep_mode) {
4305 	case USB_EP_MODE_DEFAULT:
4306 		return (0);
4307 	case USB_EP_MODE_STREAMS:
4308 		if (xhcistreams == 0 ||
4309 		    (ep->edesc->bmAttributes & UE_XFERTYPE) != UE_BULK ||
4310 		    udev->speed != USB_SPEED_SUPER)
4311 			return (USB_ERR_INVAL);
4312 		return (0);
4313 	default:
4314 		return (USB_ERR_INVAL);
4315 	}
4316 }
4317 
4318 static const struct usb_bus_methods xhci_bus_methods = {
4319 	.endpoint_init = xhci_ep_init,
4320 	.endpoint_uninit = xhci_ep_uninit,
4321 	.xfer_setup = xhci_xfer_setup,
4322 	.xfer_unsetup = xhci_xfer_unsetup,
4323 	.get_dma_delay = xhci_get_dma_delay,
4324 	.device_init = xhci_device_init,
4325 	.device_uninit = xhci_device_uninit,
4326 	.device_resume = xhci_device_resume,
4327 	.device_suspend = xhci_device_suspend,
4328 	.set_hw_power = xhci_set_hw_power,
4329 	.roothub_exec = xhci_roothub_exec,
4330 	.xfer_poll = xhci_do_poll,
4331 	.start_dma_delay = xhci_start_dma_delay,
4332 	.set_address = xhci_set_address,
4333 	.clear_stall = xhci_ep_clear_stall,
4334 	.device_state_change = xhci_device_state_change,
4335 	.set_hw_power_sleep = xhci_set_hw_power_sleep,
4336 	.set_endpoint_mode = xhci_set_endpoint_mode,
4337 };
4338