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