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