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