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