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