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