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