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