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