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