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