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