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