xref: /netbsd-src/sys/dev/usb/xhci.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: xhci.c,v 1.94 2018/07/16 23:07:31 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2013 Jonathan A. Kollasch
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
20  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
25  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * USB rev 2.0 and rev 3.1 specification
31  *  http://www.usb.org/developers/docs/
32  * xHCI rev 1.1 specification
33  *  http://www.intel.com/technology/usb/spec.htm
34  */
35 
36 #include <sys/cdefs.h>
37 __KERNEL_RCSID(0, "$NetBSD: xhci.c,v 1.94 2018/07/16 23:07:31 christos Exp $");
38 
39 #ifdef _KERNEL_OPT
40 #include "opt_usb.h"
41 #endif
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/kmem.h>
47 #include <sys/device.h>
48 #include <sys/select.h>
49 #include <sys/proc.h>
50 #include <sys/queue.h>
51 #include <sys/mutex.h>
52 #include <sys/condvar.h>
53 #include <sys/bus.h>
54 #include <sys/cpu.h>
55 #include <sys/sysctl.h>
56 
57 #include <machine/endian.h>
58 
59 #include <dev/usb/usb.h>
60 #include <dev/usb/usbdi.h>
61 #include <dev/usb/usbdivar.h>
62 #include <dev/usb/usbdi_util.h>
63 #include <dev/usb/usbhist.h>
64 #include <dev/usb/usb_mem.h>
65 #include <dev/usb/usb_quirks.h>
66 
67 #include <dev/usb/xhcireg.h>
68 #include <dev/usb/xhcivar.h>
69 #include <dev/usb/usbroothub.h>
70 
71 
72 #ifdef USB_DEBUG
73 #ifndef XHCI_DEBUG
74 #define xhcidebug 0
75 #else /* !XHCI_DEBUG */
76 #define HEXDUMP(a, b, c) \
77     do { \
78 	    if (xhcidebug > 0) \
79 		    hexdump(printf, a, b, c); \
80     } while (/*CONSTCOND*/0)
81 static int xhcidebug = 0;
82 
83 SYSCTL_SETUP(sysctl_hw_xhci_setup, "sysctl hw.xhci setup")
84 {
85 	int err;
86 	const struct sysctlnode *rnode;
87 	const struct sysctlnode *cnode;
88 
89 	err = sysctl_createv(clog, 0, NULL, &rnode,
90 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "xhci",
91 	    SYSCTL_DESCR("xhci global controls"),
92 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
93 
94 	if (err)
95 		goto fail;
96 
97 	/* control debugging printfs */
98 	err = sysctl_createv(clog, 0, &rnode, &cnode,
99 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
100 	    "debug", SYSCTL_DESCR("Enable debugging output"),
101 	    NULL, 0, &xhcidebug, sizeof(xhcidebug), CTL_CREATE, CTL_EOL);
102 	if (err)
103 		goto fail;
104 
105 	return;
106 fail:
107 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
108 }
109 
110 #endif /* !XHCI_DEBUG */
111 #endif /* USB_DEBUG */
112 
113 #ifndef HEXDUMP
114 #define HEXDUMP(a, b, c)
115 #endif
116 
117 #define DPRINTFN(N,FMT,A,B,C,D) USBHIST_LOGN(xhcidebug,N,FMT,A,B,C,D)
118 #define XHCIHIST_FUNC() USBHIST_FUNC()
119 #define XHCIHIST_CALLED(name) USBHIST_CALLED(xhcidebug)
120 
121 #define XHCI_DCI_SLOT 0
122 #define XHCI_DCI_EP_CONTROL 1
123 
124 #define XHCI_ICI_INPUT_CONTROL 0
125 
126 struct xhci_pipe {
127 	struct usbd_pipe xp_pipe;
128 	struct usb_task xp_async_task;
129 };
130 
131 #define XHCI_COMMAND_RING_TRBS 256
132 #define XHCI_EVENT_RING_TRBS 256
133 #define XHCI_EVENT_RING_SEGMENTS 1
134 #define XHCI_TRB_3_ED_BIT XHCI_TRB_3_ISP_BIT
135 
136 static usbd_status xhci_open(struct usbd_pipe *);
137 static void xhci_close_pipe(struct usbd_pipe *);
138 static int xhci_intr1(struct xhci_softc * const);
139 static void xhci_softintr(void *);
140 static void xhci_poll(struct usbd_bus *);
141 static struct usbd_xfer *xhci_allocx(struct usbd_bus *, unsigned int);
142 static void xhci_freex(struct usbd_bus *, struct usbd_xfer *);
143 static void xhci_get_lock(struct usbd_bus *, kmutex_t **);
144 static usbd_status xhci_new_device(device_t, struct usbd_bus *, int, int, int,
145     struct usbd_port *);
146 static int xhci_roothub_ctrl(struct usbd_bus *, usb_device_request_t *,
147     void *, int);
148 
149 static usbd_status xhci_configure_endpoint(struct usbd_pipe *);
150 //static usbd_status xhci_unconfigure_endpoint(struct usbd_pipe *);
151 static usbd_status xhci_reset_endpoint(struct usbd_pipe *);
152 static usbd_status xhci_stop_endpoint(struct usbd_pipe *);
153 
154 static void xhci_host_dequeue(struct xhci_ring * const);
155 static usbd_status xhci_set_dequeue(struct usbd_pipe *);
156 
157 static usbd_status xhci_do_command(struct xhci_softc * const,
158     struct xhci_trb * const, int);
159 static usbd_status xhci_do_command_locked(struct xhci_softc * const,
160     struct xhci_trb * const, int);
161 static usbd_status xhci_init_slot(struct usbd_device *, uint32_t);
162 static void xhci_free_slot(struct xhci_softc *, struct xhci_slot *, int, int);
163 static usbd_status xhci_set_address(struct usbd_device *, uint32_t, bool);
164 static usbd_status xhci_enable_slot(struct xhci_softc * const,
165     uint8_t * const);
166 static usbd_status xhci_disable_slot(struct xhci_softc * const, uint8_t);
167 static usbd_status xhci_address_device(struct xhci_softc * const,
168     uint64_t, uint8_t, bool);
169 static void xhci_set_dcba(struct xhci_softc * const, uint64_t, int);
170 static usbd_status xhci_update_ep0_mps(struct xhci_softc * const,
171     struct xhci_slot * const, u_int);
172 static usbd_status xhci_ring_init(struct xhci_softc * const,
173     struct xhci_ring * const, size_t, size_t);
174 static void xhci_ring_free(struct xhci_softc * const, struct xhci_ring * const);
175 
176 static void xhci_setup_ctx(struct usbd_pipe *);
177 static void xhci_setup_route(struct usbd_pipe *, uint32_t *);
178 static void xhci_setup_tthub(struct usbd_pipe *, uint32_t *);
179 static void xhci_setup_maxburst(struct usbd_pipe *, uint32_t *);
180 static uint32_t xhci_bival2ival(uint32_t, uint32_t);
181 
182 static void xhci_noop(struct usbd_pipe *);
183 
184 static usbd_status xhci_root_intr_transfer(struct usbd_xfer *);
185 static usbd_status xhci_root_intr_start(struct usbd_xfer *);
186 static void xhci_root_intr_abort(struct usbd_xfer *);
187 static void xhci_root_intr_close(struct usbd_pipe *);
188 static void xhci_root_intr_done(struct usbd_xfer *);
189 
190 static usbd_status xhci_device_ctrl_transfer(struct usbd_xfer *);
191 static usbd_status xhci_device_ctrl_start(struct usbd_xfer *);
192 static void xhci_device_ctrl_abort(struct usbd_xfer *);
193 static void xhci_device_ctrl_close(struct usbd_pipe *);
194 static void xhci_device_ctrl_done(struct usbd_xfer *);
195 
196 static usbd_status xhci_device_intr_transfer(struct usbd_xfer *);
197 static usbd_status xhci_device_intr_start(struct usbd_xfer *);
198 static void xhci_device_intr_abort(struct usbd_xfer *);
199 static void xhci_device_intr_close(struct usbd_pipe *);
200 static void xhci_device_intr_done(struct usbd_xfer *);
201 
202 static usbd_status xhci_device_bulk_transfer(struct usbd_xfer *);
203 static usbd_status xhci_device_bulk_start(struct usbd_xfer *);
204 static void xhci_device_bulk_abort(struct usbd_xfer *);
205 static void xhci_device_bulk_close(struct usbd_pipe *);
206 static void xhci_device_bulk_done(struct usbd_xfer *);
207 
208 static void xhci_timeout(void *);
209 static void xhci_timeout_task(void *);
210 
211 static const struct usbd_bus_methods xhci_bus_methods = {
212 	.ubm_open = xhci_open,
213 	.ubm_softint = xhci_softintr,
214 	.ubm_dopoll = xhci_poll,
215 	.ubm_allocx = xhci_allocx,
216 	.ubm_freex = xhci_freex,
217 	.ubm_getlock = xhci_get_lock,
218 	.ubm_newdev = xhci_new_device,
219 	.ubm_rhctrl = xhci_roothub_ctrl,
220 };
221 
222 static const struct usbd_pipe_methods xhci_root_intr_methods = {
223 	.upm_transfer = xhci_root_intr_transfer,
224 	.upm_start = xhci_root_intr_start,
225 	.upm_abort = xhci_root_intr_abort,
226 	.upm_close = xhci_root_intr_close,
227 	.upm_cleartoggle = xhci_noop,
228 	.upm_done = xhci_root_intr_done,
229 };
230 
231 
232 static const struct usbd_pipe_methods xhci_device_ctrl_methods = {
233 	.upm_transfer = xhci_device_ctrl_transfer,
234 	.upm_start = xhci_device_ctrl_start,
235 	.upm_abort = xhci_device_ctrl_abort,
236 	.upm_close = xhci_device_ctrl_close,
237 	.upm_cleartoggle = xhci_noop,
238 	.upm_done = xhci_device_ctrl_done,
239 };
240 
241 static const struct usbd_pipe_methods xhci_device_isoc_methods = {
242 	.upm_cleartoggle = xhci_noop,
243 };
244 
245 static const struct usbd_pipe_methods xhci_device_bulk_methods = {
246 	.upm_transfer = xhci_device_bulk_transfer,
247 	.upm_start = xhci_device_bulk_start,
248 	.upm_abort = xhci_device_bulk_abort,
249 	.upm_close = xhci_device_bulk_close,
250 	.upm_cleartoggle = xhci_noop,
251 	.upm_done = xhci_device_bulk_done,
252 };
253 
254 static const struct usbd_pipe_methods xhci_device_intr_methods = {
255 	.upm_transfer = xhci_device_intr_transfer,
256 	.upm_start = xhci_device_intr_start,
257 	.upm_abort = xhci_device_intr_abort,
258 	.upm_close = xhci_device_intr_close,
259 	.upm_cleartoggle = xhci_noop,
260 	.upm_done = xhci_device_intr_done,
261 };
262 
263 static inline uint32_t
264 xhci_read_1(const struct xhci_softc * const sc, bus_size_t offset)
265 {
266 	return bus_space_read_1(sc->sc_iot, sc->sc_ioh, offset);
267 }
268 
269 static inline uint32_t
270 xhci_read_4(const struct xhci_softc * const sc, bus_size_t offset)
271 {
272 	return bus_space_read_4(sc->sc_iot, sc->sc_ioh, offset);
273 }
274 
275 static inline void
276 xhci_write_1(const struct xhci_softc * const sc, bus_size_t offset,
277     uint32_t value)
278 {
279 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, offset, value);
280 }
281 
282 #if 0 /* unused */
283 static inline void
284 xhci_write_4(const struct xhci_softc * const sc, bus_size_t offset,
285     uint32_t value)
286 {
287 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, offset, value);
288 }
289 #endif /* unused */
290 
291 static inline uint32_t
292 xhci_cap_read_4(const struct xhci_softc * const sc, bus_size_t offset)
293 {
294 	return bus_space_read_4(sc->sc_iot, sc->sc_cbh, offset);
295 }
296 
297 static inline uint32_t
298 xhci_op_read_4(const struct xhci_softc * const sc, bus_size_t offset)
299 {
300 	return bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
301 }
302 
303 static inline void
304 xhci_op_write_4(const struct xhci_softc * const sc, bus_size_t offset,
305     uint32_t value)
306 {
307 	bus_space_write_4(sc->sc_iot, sc->sc_obh, offset, value);
308 }
309 
310 static inline uint64_t
311 xhci_op_read_8(const struct xhci_softc * const sc, bus_size_t offset)
312 {
313 	uint64_t value;
314 
315 	if (sc->sc_ac64) {
316 #ifdef XHCI_USE_BUS_SPACE_8
317 		value = bus_space_read_8(sc->sc_iot, sc->sc_obh, offset);
318 #else
319 		value = bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
320 		value |= (uint64_t)bus_space_read_4(sc->sc_iot, sc->sc_obh,
321 		    offset + 4) << 32;
322 #endif
323 	} else {
324 		value = bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
325 	}
326 
327 	return value;
328 }
329 
330 static inline void
331 xhci_op_write_8(const struct xhci_softc * const sc, bus_size_t offset,
332     uint64_t value)
333 {
334 	if (sc->sc_ac64) {
335 #ifdef XHCI_USE_BUS_SPACE_8
336 		bus_space_write_8(sc->sc_iot, sc->sc_obh, offset, value);
337 #else
338 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset + 0,
339 		    (value >> 0) & 0xffffffff);
340 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset + 4,
341 		    (value >> 32) & 0xffffffff);
342 #endif
343 	} else {
344 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset, value);
345 	}
346 }
347 
348 static inline uint32_t
349 xhci_rt_read_4(const struct xhci_softc * const sc, bus_size_t offset)
350 {
351 	return bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
352 }
353 
354 static inline void
355 xhci_rt_write_4(const struct xhci_softc * const sc, bus_size_t offset,
356     uint32_t value)
357 {
358 	bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset, value);
359 }
360 
361 #if 0 /* unused */
362 static inline uint64_t
363 xhci_rt_read_8(const struct xhci_softc * const sc, bus_size_t offset)
364 {
365 	uint64_t value;
366 
367 	if (sc->sc_ac64) {
368 #ifdef XHCI_USE_BUS_SPACE_8
369 		value = bus_space_read_8(sc->sc_iot, sc->sc_rbh, offset);
370 #else
371 		value = bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
372 		value |= (uint64_t)bus_space_read_4(sc->sc_iot, sc->sc_rbh,
373 		    offset + 4) << 32;
374 #endif
375 	} else {
376 		value = bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
377 	}
378 
379 	return value;
380 }
381 #endif /* unused */
382 
383 static inline void
384 xhci_rt_write_8(const struct xhci_softc * const sc, bus_size_t offset,
385     uint64_t value)
386 {
387 	if (sc->sc_ac64) {
388 #ifdef XHCI_USE_BUS_SPACE_8
389 		bus_space_write_8(sc->sc_iot, sc->sc_rbh, offset, value);
390 #else
391 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset + 0,
392 		    (value >> 0) & 0xffffffff);
393 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset + 4,
394 		    (value >> 32) & 0xffffffff);
395 #endif
396 	} else {
397 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset, value);
398 	}
399 }
400 
401 #if 0 /* unused */
402 static inline uint32_t
403 xhci_db_read_4(const struct xhci_softc * const sc, bus_size_t offset)
404 {
405 	return bus_space_read_4(sc->sc_iot, sc->sc_dbh, offset);
406 }
407 #endif /* unused */
408 
409 static inline void
410 xhci_db_write_4(const struct xhci_softc * const sc, bus_size_t offset,
411     uint32_t value)
412 {
413 	bus_space_write_4(sc->sc_iot, sc->sc_dbh, offset, value);
414 }
415 
416 /* --- */
417 
418 static inline uint8_t
419 xhci_ep_get_type(usb_endpoint_descriptor_t * const ed)
420 {
421 	u_int eptype = 0;
422 
423 	switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
424 	case UE_CONTROL:
425 		eptype = 0x0;
426 		break;
427 	case UE_ISOCHRONOUS:
428 		eptype = 0x1;
429 		break;
430 	case UE_BULK:
431 		eptype = 0x2;
432 		break;
433 	case UE_INTERRUPT:
434 		eptype = 0x3;
435 		break;
436 	}
437 
438 	if ((UE_GET_XFERTYPE(ed->bmAttributes) == UE_CONTROL) ||
439 	    (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN))
440 		return eptype | 0x4;
441 	else
442 		return eptype;
443 }
444 
445 static u_int
446 xhci_ep_get_dci(usb_endpoint_descriptor_t * const ed)
447 {
448 	/* xHCI 1.0 section 4.5.1 */
449 	u_int epaddr = UE_GET_ADDR(ed->bEndpointAddress);
450 	u_int in = 0;
451 
452 	if ((UE_GET_XFERTYPE(ed->bmAttributes) == UE_CONTROL) ||
453 	    (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN))
454 		in = 1;
455 
456 	return epaddr * 2 + in;
457 }
458 
459 static inline u_int
460 xhci_dci_to_ici(const u_int i)
461 {
462 	return i + 1;
463 }
464 
465 static inline void *
466 xhci_slot_get_dcv(struct xhci_softc * const sc, struct xhci_slot * const xs,
467     const u_int dci)
468 {
469 	return KERNADDR(&xs->xs_dc_dma, sc->sc_ctxsz * dci);
470 }
471 
472 #if 0 /* unused */
473 static inline bus_addr_t
474 xhci_slot_get_dcp(struct xhci_softc * const sc, struct xhci_slot * const xs,
475     const u_int dci)
476 {
477 	return DMAADDR(&xs->xs_dc_dma, sc->sc_ctxsz * dci);
478 }
479 #endif /* unused */
480 
481 static inline void *
482 xhci_slot_get_icv(struct xhci_softc * const sc, struct xhci_slot * const xs,
483     const u_int ici)
484 {
485 	return KERNADDR(&xs->xs_ic_dma, sc->sc_ctxsz * ici);
486 }
487 
488 static inline bus_addr_t
489 xhci_slot_get_icp(struct xhci_softc * const sc, struct xhci_slot * const xs,
490     const u_int ici)
491 {
492 	return DMAADDR(&xs->xs_ic_dma, sc->sc_ctxsz * ici);
493 }
494 
495 static inline struct xhci_trb *
496 xhci_ring_trbv(struct xhci_ring * const xr, u_int idx)
497 {
498 	return KERNADDR(&xr->xr_dma, XHCI_TRB_SIZE * idx);
499 }
500 
501 static inline bus_addr_t
502 xhci_ring_trbp(struct xhci_ring * const xr, u_int idx)
503 {
504 	return DMAADDR(&xr->xr_dma, XHCI_TRB_SIZE * idx);
505 }
506 
507 static inline void
508 xhci_trb_put(struct xhci_trb * const trb, uint64_t parameter, uint32_t status,
509     uint32_t control)
510 {
511 	trb->trb_0 = htole64(parameter);
512 	trb->trb_2 = htole32(status);
513 	trb->trb_3 = htole32(control);
514 }
515 
516 static int
517 xhci_trb_get_idx(struct xhci_ring *xr, uint64_t trb_0, int *idx)
518 {
519 	/* base address of TRBs */
520 	bus_addr_t trbp = xhci_ring_trbp(xr, 0);
521 
522 	/* trb_0 range sanity check */
523 	if (trb_0 == 0 || trb_0 < trbp ||
524 	    (trb_0 - trbp) % sizeof(struct xhci_trb) != 0 ||
525 	    (trb_0 - trbp) / sizeof(struct xhci_trb) >= xr->xr_ntrb) {
526 		return 1;
527 	}
528 	*idx = (trb_0 - trbp) / sizeof(struct xhci_trb);
529 	return 0;
530 }
531 
532 static unsigned int
533 xhci_get_epstate(struct xhci_softc * const sc, struct xhci_slot * const xs,
534     u_int dci)
535 {
536 	uint32_t *cp;
537 
538 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
539 	cp = xhci_slot_get_dcv(sc, xs, dci);
540 	return XHCI_EPCTX_0_EPSTATE_GET(le32toh(cp[0]));
541 }
542 
543 static inline unsigned int
544 xhci_ctlrport2bus(struct xhci_softc * const sc, unsigned int ctlrport)
545 {
546 	const unsigned int port = ctlrport - 1;
547 	const uint8_t bit = __BIT(port % NBBY);
548 
549 	return __SHIFTOUT(sc->sc_ctlrportbus[port / NBBY], bit);
550 }
551 
552 /*
553  * Return the roothub port for a controller port.  Both are 1..n.
554  */
555 static inline unsigned int
556 xhci_ctlrport2rhport(struct xhci_softc * const sc, unsigned int ctrlport)
557 {
558 
559 	return sc->sc_ctlrportmap[ctrlport - 1];
560 }
561 
562 /*
563  * Return the controller port for a bus roothub port.  Both are 1..n.
564  */
565 static inline unsigned int
566 xhci_rhport2ctlrport(struct xhci_softc * const sc, unsigned int bn,
567     unsigned int rhport)
568 {
569 
570 	return sc->sc_rhportmap[bn][rhport - 1];
571 }
572 
573 /* --- */
574 
575 void
576 xhci_childdet(device_t self, device_t child)
577 {
578 	struct xhci_softc * const sc = device_private(self);
579 
580 	KASSERT((sc->sc_child == child) || (sc->sc_child2 == child));
581 	if (child == sc->sc_child2)
582 		sc->sc_child2 = NULL;
583 	else if (child == sc->sc_child)
584 		sc->sc_child = NULL;
585 }
586 
587 int
588 xhci_detach(struct xhci_softc *sc, int flags)
589 {
590 	int rv = 0;
591 
592 	if (sc->sc_child2 != NULL) {
593 		rv = config_detach(sc->sc_child2, flags);
594 		if (rv != 0)
595 			return rv;
596 		KASSERT(sc->sc_child2 == NULL);
597 	}
598 
599 	if (sc->sc_child != NULL) {
600 		rv = config_detach(sc->sc_child, flags);
601 		if (rv != 0)
602 			return rv;
603 		KASSERT(sc->sc_child == NULL);
604 	}
605 
606 	/* XXX unconfigure/free slots */
607 
608 	/* verify: */
609 	xhci_rt_write_4(sc, XHCI_IMAN(0), 0);
610 	xhci_op_write_4(sc, XHCI_USBCMD, 0);
611 	/* do we need to wait for stop? */
612 
613 	xhci_op_write_8(sc, XHCI_CRCR, 0);
614 	xhci_ring_free(sc, &sc->sc_cr);
615 	cv_destroy(&sc->sc_command_cv);
616 	cv_destroy(&sc->sc_cmdbusy_cv);
617 
618 	xhci_rt_write_4(sc, XHCI_ERSTSZ(0), 0);
619 	xhci_rt_write_8(sc, XHCI_ERSTBA(0), 0);
620 	xhci_rt_write_8(sc, XHCI_ERDP(0), 0|XHCI_ERDP_LO_BUSY);
621 	xhci_ring_free(sc, &sc->sc_er);
622 
623 	usb_freemem(&sc->sc_bus, &sc->sc_eventst_dma);
624 
625 	xhci_op_write_8(sc, XHCI_DCBAAP, 0);
626 	usb_freemem(&sc->sc_bus, &sc->sc_dcbaa_dma);
627 
628 	kmem_free(sc->sc_slots, sizeof(*sc->sc_slots) * sc->sc_maxslots);
629 
630 	kmem_free(sc->sc_ctlrportbus,
631 	    howmany(sc->sc_maxports * sizeof(uint8_t), NBBY));
632 	kmem_free(sc->sc_ctlrportmap, sc->sc_maxports * sizeof(int));
633 
634 	for (size_t j = 0; j < __arraycount(sc->sc_rhportmap); j++) {
635 		kmem_free(sc->sc_rhportmap[j], sc->sc_maxports * sizeof(int));
636 	}
637 
638 	mutex_destroy(&sc->sc_lock);
639 	mutex_destroy(&sc->sc_intr_lock);
640 
641 	pool_cache_destroy(sc->sc_xferpool);
642 
643 	return rv;
644 }
645 
646 int
647 xhci_activate(device_t self, enum devact act)
648 {
649 	struct xhci_softc * const sc = device_private(self);
650 
651 	switch (act) {
652 	case DVACT_DEACTIVATE:
653 		sc->sc_dying = true;
654 		return 0;
655 	default:
656 		return EOPNOTSUPP;
657 	}
658 }
659 
660 bool
661 xhci_suspend(device_t dv, const pmf_qual_t *qual)
662 {
663 	return false;
664 }
665 
666 bool
667 xhci_resume(device_t dv, const pmf_qual_t *qual)
668 {
669 	return false;
670 }
671 
672 bool
673 xhci_shutdown(device_t self, int flags)
674 {
675 	return false;
676 }
677 
678 static int
679 xhci_hc_reset(struct xhci_softc * const sc)
680 {
681 	uint32_t usbcmd, usbsts;
682 	int i;
683 
684 	/* Check controller not ready */
685 	for (i = 0; i < XHCI_WAIT_CNR; i++) {
686 		usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
687 		if ((usbsts & XHCI_STS_CNR) == 0)
688 			break;
689 		usb_delay_ms(&sc->sc_bus, 1);
690 	}
691 	if (i >= XHCI_WAIT_CNR) {
692 		aprint_error_dev(sc->sc_dev, "controller not ready timeout\n");
693 		return EIO;
694 	}
695 
696 	/* Halt controller */
697 	usbcmd = 0;
698 	xhci_op_write_4(sc, XHCI_USBCMD, usbcmd);
699 	usb_delay_ms(&sc->sc_bus, 1);
700 
701 	/* Reset controller */
702 	usbcmd = XHCI_CMD_HCRST;
703 	xhci_op_write_4(sc, XHCI_USBCMD, usbcmd);
704 	for (i = 0; i < XHCI_WAIT_HCRST; i++) {
705 		/*
706 		 * Wait 1ms first. Existing Intel xHCI requies 1ms delay to
707 		 * prevent system hang (Errata).
708 		 */
709 		usb_delay_ms(&sc->sc_bus, 1);
710 		usbcmd = xhci_op_read_4(sc, XHCI_USBCMD);
711 		if ((usbcmd & XHCI_CMD_HCRST) == 0)
712 			break;
713 	}
714 	if (i >= XHCI_WAIT_HCRST) {
715 		aprint_error_dev(sc->sc_dev, "host controller reset timeout\n");
716 		return EIO;
717 	}
718 
719 	/* Check controller not ready */
720 	for (i = 0; i < XHCI_WAIT_CNR; i++) {
721 		usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
722 		if ((usbsts & XHCI_STS_CNR) == 0)
723 			break;
724 		usb_delay_ms(&sc->sc_bus, 1);
725 	}
726 	if (i >= XHCI_WAIT_CNR) {
727 		aprint_error_dev(sc->sc_dev,
728 		    "controller not ready timeout after reset\n");
729 		return EIO;
730 	}
731 
732 	return 0;
733 }
734 
735 
736 /* 7.2 xHCI Support Protocol Capability */
737 static void
738 xhci_id_protocols(struct xhci_softc *sc, bus_size_t ecp)
739 {
740 	/* XXX Cache this lot */
741 
742 	const uint32_t w0 = xhci_read_4(sc, ecp);
743 	const uint32_t w4 = xhci_read_4(sc, ecp + 4);
744 	const uint32_t w8 = xhci_read_4(sc, ecp + 8);
745 	const uint32_t wc = xhci_read_4(sc, ecp + 0xc);
746 
747 	aprint_debug_dev(sc->sc_dev,
748 	    " SP: %08x %08x %08x %08x\n", w0, w4, w8, wc);
749 
750 	if (w4 != XHCI_XECP_USBID)
751 		return;
752 
753 	const int major = XHCI_XECP_SP_W0_MAJOR(w0);
754 	const int minor = XHCI_XECP_SP_W0_MINOR(w0);
755 	const uint8_t cpo = XHCI_XECP_SP_W8_CPO(w8);
756 	const uint8_t cpc = XHCI_XECP_SP_W8_CPC(w8);
757 
758 	const uint16_t mm = __SHIFTOUT(w0, __BITS(31, 16));
759 	switch (mm) {
760 	case 0x0200:
761 	case 0x0300:
762 	case 0x0301:
763 		aprint_debug_dev(sc->sc_dev, " %s ports %d - %d\n",
764 		    major == 3 ? "ss" : "hs", cpo, cpo + cpc -1);
765 		break;
766 	default:
767 		aprint_debug_dev(sc->sc_dev, " unknown major/minor (%d/%d)\n",
768 		    major, minor);
769 		return;
770 	}
771 
772 	const size_t bus = (major == 3) ? 0 : 1;
773 
774 	/* Index arrays with 0..n-1 where ports are numbered 1..n */
775 	for (size_t cp = cpo - 1; cp < cpo + cpc - 1; cp++) {
776 		if (sc->sc_ctlrportmap[cp] != 0) {
777 			aprint_error_dev(sc->sc_dev, "contoller port %zu "
778 			    "already assigned", cp);
779 			continue;
780 		}
781 
782 		sc->sc_ctlrportbus[cp / NBBY] |=
783 		    bus == 0 ? 0 : __BIT(cp % NBBY);
784 
785 		const size_t rhp = sc->sc_rhportcount[bus]++;
786 
787 		KASSERTMSG(sc->sc_rhportmap[bus][rhp] == 0,
788 		    "bus %zu rhp %zu is %d", bus, rhp,
789 		    sc->sc_rhportmap[bus][rhp]);
790 
791 		sc->sc_rhportmap[bus][rhp] = cp + 1;
792 		sc->sc_ctlrportmap[cp] = rhp + 1;
793 	}
794 }
795 
796 /* Process extended capabilities */
797 static void
798 xhci_ecp(struct xhci_softc *sc, uint32_t hcc)
799 {
800 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
801 
802 	bus_size_t ecp = XHCI_HCC_XECP(hcc) * 4;
803 	while (ecp != 0) {
804 		uint32_t ecr = xhci_read_4(sc, ecp);
805 		aprint_debug_dev(sc->sc_dev, "ECR: 0x%08x\n", ecr);
806 		switch (XHCI_XECP_ID(ecr)) {
807 		case XHCI_ID_PROTOCOLS: {
808 			xhci_id_protocols(sc, ecp);
809 			break;
810 		}
811 		case XHCI_ID_USB_LEGACY: {
812 			uint8_t bios_sem;
813 
814 			/* Take host controller ownership from BIOS */
815 			bios_sem = xhci_read_1(sc, ecp + XHCI_XECP_BIOS_SEM);
816 			if (bios_sem) {
817 				/* sets xHCI to be owned by OS */
818 				xhci_write_1(sc, ecp + XHCI_XECP_OS_SEM, 1);
819 				aprint_debug_dev(sc->sc_dev,
820 				    "waiting for BIOS to give up control\n");
821 				for (int i = 0; i < 5000; i++) {
822 					bios_sem = xhci_read_1(sc, ecp +
823 					    XHCI_XECP_BIOS_SEM);
824 					if (bios_sem == 0)
825 						break;
826 					DELAY(1000);
827 				}
828 				if (bios_sem) {
829 					aprint_error_dev(sc->sc_dev,
830 					    "timed out waiting for BIOS\n");
831 				}
832 			}
833 			break;
834 		}
835 		default:
836 			break;
837 		}
838 		ecr = xhci_read_4(sc, ecp);
839 		if (XHCI_XECP_NEXT(ecr) == 0) {
840 			ecp = 0;
841 		} else {
842 			ecp += XHCI_XECP_NEXT(ecr) * 4;
843 		}
844 	}
845 }
846 
847 #define XHCI_HCCPREV1_BITS	\
848 	"\177\020"	/* New bitmask */			\
849 	"f\020\020XECP\0"					\
850 	"f\014\4MAXPSA\0"					\
851 	"b\013CFC\0"						\
852 	"b\012SEC\0"						\
853 	"b\011SBD\0"						\
854 	"b\010FSE\0"						\
855 	"b\7NSS\0"						\
856 	"b\6LTC\0"						\
857 	"b\5LHRC\0"						\
858 	"b\4PIND\0"						\
859 	"b\3PPC\0"						\
860 	"b\2CZC\0"						\
861 	"b\1BNC\0"						\
862 	"b\0AC64\0"						\
863 	"\0"
864 #define XHCI_HCCV1_x_BITS	\
865 	"\177\020"	/* New bitmask */			\
866 	"f\020\020XECP\0"					\
867 	"f\014\4MAXPSA\0"					\
868 	"b\013CFC\0"						\
869 	"b\012SEC\0"						\
870 	"b\011SPC\0"						\
871 	"b\010PAE\0"						\
872 	"b\7NSS\0"						\
873 	"b\6LTC\0"						\
874 	"b\5LHRC\0"						\
875 	"b\4PIND\0"						\
876 	"b\3PPC\0"						\
877 	"b\2CSZ\0"						\
878 	"b\1BNC\0"						\
879 	"b\0AC64\0"						\
880 	"\0"
881 
882 void
883 xhci_start(struct xhci_softc *sc)
884 {
885 	xhci_rt_write_4(sc, XHCI_IMAN(0), XHCI_IMAN_INTR_ENA);
886 	if ((sc->sc_quirks & XHCI_QUIRK_INTEL) != 0)
887 		/* Intel xhci needs interrupt rate moderated. */
888 		xhci_rt_write_4(sc, XHCI_IMOD(0), XHCI_IMOD_DEFAULT_LP);
889 	else
890 		xhci_rt_write_4(sc, XHCI_IMOD(0), 0);
891 	aprint_debug_dev(sc->sc_dev, "current IMOD %u\n",
892 	    xhci_rt_read_4(sc, XHCI_IMOD(0)));
893 
894 	xhci_op_write_4(sc, XHCI_USBCMD, XHCI_CMD_INTE|XHCI_CMD_RS); /* Go! */
895 	aprint_debug_dev(sc->sc_dev, "USBCMD %08"PRIx32"\n",
896 	    xhci_op_read_4(sc, XHCI_USBCMD));
897 }
898 
899 int
900 xhci_init(struct xhci_softc *sc)
901 {
902 	bus_size_t bsz;
903 	uint32_t cap, hcs1, hcs2, hcs3, hcc, dboff, rtsoff;
904 	uint32_t pagesize, config;
905 	int i = 0;
906 	uint16_t hciversion;
907 	uint8_t caplength;
908 
909 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
910 
911 	/* Set up the bus struct for the usb 3 and usb 2 buses */
912 	sc->sc_bus.ub_methods = &xhci_bus_methods;
913 	sc->sc_bus.ub_pipesize = sizeof(struct xhci_pipe);
914 	sc->sc_bus.ub_usedma = true;
915 	sc->sc_bus.ub_hcpriv = sc;
916 
917 	sc->sc_bus2.ub_methods = &xhci_bus_methods;
918 	sc->sc_bus2.ub_pipesize = sizeof(struct xhci_pipe);
919 	sc->sc_bus2.ub_revision = USBREV_2_0;
920 	sc->sc_bus2.ub_usedma = true;
921 	sc->sc_bus2.ub_hcpriv = sc;
922 	sc->sc_bus2.ub_dmatag = sc->sc_bus.ub_dmatag;
923 
924 	cap = xhci_read_4(sc, XHCI_CAPLENGTH);
925 	caplength = XHCI_CAP_CAPLENGTH(cap);
926 	hciversion = XHCI_CAP_HCIVERSION(cap);
927 
928 	if (hciversion < XHCI_HCIVERSION_0_96 ||
929 	    hciversion > XHCI_HCIVERSION_1_0) {
930 		aprint_normal_dev(sc->sc_dev,
931 		    "xHCI version %x.%x not known to be supported\n",
932 		    (hciversion >> 8) & 0xff, (hciversion >> 0) & 0xff);
933 	} else {
934 		aprint_verbose_dev(sc->sc_dev, "xHCI version %x.%x\n",
935 		    (hciversion >> 8) & 0xff, (hciversion >> 0) & 0xff);
936 	}
937 
938 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, 0, caplength,
939 	    &sc->sc_cbh) != 0) {
940 		aprint_error_dev(sc->sc_dev, "capability subregion failure\n");
941 		return ENOMEM;
942 	}
943 
944 	hcs1 = xhci_cap_read_4(sc, XHCI_HCSPARAMS1);
945 	sc->sc_maxslots = XHCI_HCS1_MAXSLOTS(hcs1);
946 	sc->sc_maxintrs = XHCI_HCS1_MAXINTRS(hcs1);
947 	sc->sc_maxports = XHCI_HCS1_MAXPORTS(hcs1);
948 	hcs2 = xhci_cap_read_4(sc, XHCI_HCSPARAMS2);
949 	hcs3 = xhci_cap_read_4(sc, XHCI_HCSPARAMS3);
950 	aprint_debug_dev(sc->sc_dev,
951 	    "hcs1=%"PRIx32" hcs2=%"PRIx32" hcs3=%"PRIx32"\n", hcs1, hcs2, hcs3);
952 
953 	hcc = xhci_cap_read_4(sc, XHCI_HCCPARAMS);
954 	sc->sc_ac64 = XHCI_HCC_AC64(hcc);
955 	sc->sc_ctxsz = XHCI_HCC_CSZ(hcc) ? 64 : 32;
956 
957 	char sbuf[128];
958 	if (hciversion < XHCI_HCIVERSION_1_0)
959 		snprintb(sbuf, sizeof(sbuf), XHCI_HCCPREV1_BITS, hcc);
960 	else
961 		snprintb(sbuf, sizeof(sbuf), XHCI_HCCV1_x_BITS, hcc);
962 	aprint_debug_dev(sc->sc_dev, "hcc=%s\n", sbuf);
963 	aprint_debug_dev(sc->sc_dev, "xECP %x\n", XHCI_HCC_XECP(hcc) * 4);
964 
965 	/* default all ports to bus 0, i.e. usb 3 */
966 	sc->sc_ctlrportbus = kmem_zalloc(
967 	    howmany(sc->sc_maxports * sizeof(uint8_t), NBBY), KM_SLEEP);
968 	sc->sc_ctlrportmap = kmem_zalloc(sc->sc_maxports * sizeof(int), KM_SLEEP);
969 
970 	/* controller port to bus roothub port map */
971 	for (size_t j = 0; j < __arraycount(sc->sc_rhportmap); j++) {
972 		sc->sc_rhportmap[j] = kmem_zalloc(sc->sc_maxports * sizeof(int), KM_SLEEP);
973 	}
974 
975 	/*
976 	 * Process all Extended Capabilities
977 	 */
978 	xhci_ecp(sc, hcc);
979 
980 	bsz = XHCI_PORTSC(sc->sc_maxports);
981 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, caplength, bsz,
982 	    &sc->sc_obh) != 0) {
983 		aprint_error_dev(sc->sc_dev, "operational subregion failure\n");
984 		return ENOMEM;
985 	}
986 
987 	dboff = xhci_cap_read_4(sc, XHCI_DBOFF);
988 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, dboff,
989 	    sc->sc_maxslots * 4, &sc->sc_dbh) != 0) {
990 		aprint_error_dev(sc->sc_dev, "doorbell subregion failure\n");
991 		return ENOMEM;
992 	}
993 
994 	rtsoff = xhci_cap_read_4(sc, XHCI_RTSOFF);
995 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, rtsoff,
996 	    sc->sc_maxintrs * 0x20, &sc->sc_rbh) != 0) {
997 		aprint_error_dev(sc->sc_dev, "runtime subregion failure\n");
998 		return ENOMEM;
999 	}
1000 
1001 	int rv;
1002 	rv = xhci_hc_reset(sc);
1003 	if (rv != 0) {
1004 		return rv;
1005 	}
1006 
1007 	if (sc->sc_vendor_init)
1008 		sc->sc_vendor_init(sc);
1009 
1010 	pagesize = xhci_op_read_4(sc, XHCI_PAGESIZE);
1011 	aprint_debug_dev(sc->sc_dev, "PAGESIZE 0x%08x\n", pagesize);
1012 	pagesize = ffs(pagesize);
1013 	if (pagesize == 0) {
1014 		aprint_error_dev(sc->sc_dev, "pagesize is 0\n");
1015 		return EIO;
1016 	}
1017 	sc->sc_pgsz = 1 << (12 + (pagesize - 1));
1018 	aprint_debug_dev(sc->sc_dev, "sc_pgsz 0x%08x\n", (uint32_t)sc->sc_pgsz);
1019 	aprint_debug_dev(sc->sc_dev, "sc_maxslots 0x%08x\n",
1020 	    (uint32_t)sc->sc_maxslots);
1021 	aprint_debug_dev(sc->sc_dev, "sc_maxports %d\n", sc->sc_maxports);
1022 
1023 	usbd_status err;
1024 
1025 	sc->sc_maxspbuf = XHCI_HCS2_MAXSPBUF(hcs2);
1026 	aprint_debug_dev(sc->sc_dev, "sc_maxspbuf %d\n", sc->sc_maxspbuf);
1027 	if (sc->sc_maxspbuf != 0) {
1028 		err = usb_allocmem(&sc->sc_bus,
1029 		    sizeof(uint64_t) * sc->sc_maxspbuf, sizeof(uint64_t),
1030 		    &sc->sc_spbufarray_dma);
1031 		if (err) {
1032 			aprint_error_dev(sc->sc_dev,
1033 			    "spbufarray init fail, err %d\n", err);
1034 			return ENOMEM;
1035 		}
1036 
1037 		sc->sc_spbuf_dma = kmem_zalloc(sizeof(*sc->sc_spbuf_dma) *
1038 		    sc->sc_maxspbuf, KM_SLEEP);
1039 		uint64_t *spbufarray = KERNADDR(&sc->sc_spbufarray_dma, 0);
1040 		for (i = 0; i < sc->sc_maxspbuf; i++) {
1041 			usb_dma_t * const dma = &sc->sc_spbuf_dma[i];
1042 			/* allocate contexts */
1043 			err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz,
1044 			    sc->sc_pgsz, dma);
1045 			if (err) {
1046 				aprint_error_dev(sc->sc_dev,
1047 				    "spbufarray_dma init fail, err %d\n", err);
1048 				rv = ENOMEM;
1049 				goto bad1;
1050 			}
1051 			spbufarray[i] = htole64(DMAADDR(dma, 0));
1052 			usb_syncmem(dma, 0, sc->sc_pgsz,
1053 			    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
1054 		}
1055 
1056 		usb_syncmem(&sc->sc_spbufarray_dma, 0,
1057 		    sizeof(uint64_t) * sc->sc_maxspbuf, BUS_DMASYNC_PREWRITE);
1058 	}
1059 
1060 	config = xhci_op_read_4(sc, XHCI_CONFIG);
1061 	config &= ~0xFF;
1062 	config |= sc->sc_maxslots & 0xFF;
1063 	xhci_op_write_4(sc, XHCI_CONFIG, config);
1064 
1065 	err = xhci_ring_init(sc, &sc->sc_cr, XHCI_COMMAND_RING_TRBS,
1066 	    XHCI_COMMAND_RING_SEGMENTS_ALIGN);
1067 	if (err) {
1068 		aprint_error_dev(sc->sc_dev, "command ring init fail, err %d\n",
1069 		    err);
1070 		rv = ENOMEM;
1071 		goto bad1;
1072 	}
1073 
1074 	err = xhci_ring_init(sc, &sc->sc_er, XHCI_EVENT_RING_TRBS,
1075 	    XHCI_EVENT_RING_SEGMENTS_ALIGN);
1076 	if (err) {
1077 		aprint_error_dev(sc->sc_dev, "event ring init fail, err %d\n",
1078 		    err);
1079 		rv = ENOMEM;
1080 		goto bad2;
1081 	}
1082 
1083 	usb_dma_t *dma;
1084 	size_t size;
1085 	size_t align;
1086 
1087 	dma = &sc->sc_eventst_dma;
1088 	size = roundup2(XHCI_EVENT_RING_SEGMENTS * XHCI_ERSTE_SIZE,
1089 	    XHCI_EVENT_RING_SEGMENT_TABLE_ALIGN);
1090 	KASSERTMSG(size <= (512 * 1024), "eventst size %zu too large", size);
1091 	align = XHCI_EVENT_RING_SEGMENT_TABLE_ALIGN;
1092 	err = usb_allocmem(&sc->sc_bus, size, align, dma);
1093 	if (err) {
1094 		aprint_error_dev(sc->sc_dev, "eventst init fail, err %d\n",
1095 		    err);
1096 		rv = ENOMEM;
1097 		goto bad3;
1098 	}
1099 
1100 	memset(KERNADDR(dma, 0), 0, size);
1101 	usb_syncmem(dma, 0, size, BUS_DMASYNC_PREWRITE);
1102 	aprint_debug_dev(sc->sc_dev, "eventst: %016jx %p %zx\n",
1103 	    (uintmax_t)DMAADDR(&sc->sc_eventst_dma, 0),
1104 	    KERNADDR(&sc->sc_eventst_dma, 0),
1105 	    sc->sc_eventst_dma.udma_block->size);
1106 
1107 	dma = &sc->sc_dcbaa_dma;
1108 	size = (1 + sc->sc_maxslots) * sizeof(uint64_t);
1109 	KASSERTMSG(size <= 2048, "dcbaa size %zu too large", size);
1110 	align = XHCI_DEVICE_CONTEXT_BASE_ADDRESS_ARRAY_ALIGN;
1111 	err = usb_allocmem(&sc->sc_bus, size, align, dma);
1112 	if (err) {
1113 		aprint_error_dev(sc->sc_dev, "dcbaa init fail, err %d\n", err);
1114 		rv = ENOMEM;
1115 		goto bad4;
1116 	}
1117 	aprint_debug_dev(sc->sc_dev, "dcbaa: %016jx %p %zx\n",
1118 	    (uintmax_t)DMAADDR(&sc->sc_dcbaa_dma, 0),
1119 	    KERNADDR(&sc->sc_dcbaa_dma, 0),
1120 	    sc->sc_dcbaa_dma.udma_block->size);
1121 
1122 	memset(KERNADDR(dma, 0), 0, size);
1123 	if (sc->sc_maxspbuf != 0) {
1124 		/*
1125 		 * DCBA entry 0 hold the scratchbuf array pointer.
1126 		 */
1127 		*(uint64_t *)KERNADDR(dma, 0) =
1128 		    htole64(DMAADDR(&sc->sc_spbufarray_dma, 0));
1129 	}
1130 	usb_syncmem(dma, 0, size, BUS_DMASYNC_PREWRITE);
1131 
1132 	sc->sc_slots = kmem_zalloc(sizeof(*sc->sc_slots) * sc->sc_maxslots,
1133 	    KM_SLEEP);
1134 	if (sc->sc_slots == NULL) {
1135 		aprint_error_dev(sc->sc_dev, "slots init fail, err %d\n", err);
1136 		rv = ENOMEM;
1137 		goto bad;
1138 	}
1139 
1140 	sc->sc_xferpool = pool_cache_init(sizeof(struct xhci_xfer), 0, 0, 0,
1141 	    "xhcixfer", NULL, IPL_USB, NULL, NULL, NULL);
1142 	if (sc->sc_xferpool == NULL) {
1143 		aprint_error_dev(sc->sc_dev, "pool_cache init fail, err %d\n",
1144 		    err);
1145 		rv = ENOMEM;
1146 		goto bad;
1147 	}
1148 
1149 	cv_init(&sc->sc_command_cv, "xhcicmd");
1150 	cv_init(&sc->sc_cmdbusy_cv, "xhcicmdq");
1151 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
1152 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_USB);
1153 
1154 	struct xhci_erste *erst;
1155 	erst = KERNADDR(&sc->sc_eventst_dma, 0);
1156 	erst[0].erste_0 = htole64(xhci_ring_trbp(&sc->sc_er, 0));
1157 	erst[0].erste_2 = htole32(sc->sc_er.xr_ntrb);
1158 	erst[0].erste_3 = htole32(0);
1159 	usb_syncmem(&sc->sc_eventst_dma, 0,
1160 	    XHCI_ERSTE_SIZE * XHCI_EVENT_RING_SEGMENTS, BUS_DMASYNC_PREWRITE);
1161 
1162 	xhci_rt_write_4(sc, XHCI_ERSTSZ(0), XHCI_EVENT_RING_SEGMENTS);
1163 	xhci_rt_write_8(sc, XHCI_ERSTBA(0), DMAADDR(&sc->sc_eventst_dma, 0));
1164 	xhci_rt_write_8(sc, XHCI_ERDP(0), xhci_ring_trbp(&sc->sc_er, 0) |
1165 	    XHCI_ERDP_LO_BUSY);
1166 	xhci_op_write_8(sc, XHCI_DCBAAP, DMAADDR(&sc->sc_dcbaa_dma, 0));
1167 	xhci_op_write_8(sc, XHCI_CRCR, xhci_ring_trbp(&sc->sc_cr, 0) |
1168 	    sc->sc_cr.xr_cs);
1169 
1170 	HEXDUMP("eventst", KERNADDR(&sc->sc_eventst_dma, 0),
1171 	    XHCI_ERSTE_SIZE * XHCI_EVENT_RING_SEGMENTS);
1172 
1173 	if ((sc->sc_quirks & XHCI_DEFERRED_START) == 0)
1174 		xhci_start(sc);
1175 
1176 	return 0;
1177 
1178  bad:
1179 	if (sc->sc_xferpool) {
1180 		pool_cache_destroy(sc->sc_xferpool);
1181 		sc->sc_xferpool = NULL;
1182 	}
1183 
1184 	if (sc->sc_slots) {
1185 		kmem_free(sc->sc_slots, sizeof(*sc->sc_slots) *
1186 		    sc->sc_maxslots);
1187 		sc->sc_slots = NULL;
1188 	}
1189 
1190 	usb_freemem(&sc->sc_bus, &sc->sc_dcbaa_dma);
1191  bad4:
1192 	usb_freemem(&sc->sc_bus, &sc->sc_eventst_dma);
1193  bad3:
1194 	xhci_ring_free(sc, &sc->sc_er);
1195  bad2:
1196 	xhci_ring_free(sc, &sc->sc_cr);
1197 	i = sc->sc_maxspbuf;
1198  bad1:
1199 	for (int j = 0; j < i; j++)
1200 		usb_freemem(&sc->sc_bus, &sc->sc_spbuf_dma[j]);
1201 	usb_freemem(&sc->sc_bus, &sc->sc_spbufarray_dma);
1202 
1203 	return rv;
1204 }
1205 
1206 static inline bool
1207 xhci_polling_p(struct xhci_softc * const sc)
1208 {
1209 	return sc->sc_bus.ub_usepolling || sc->sc_bus2.ub_usepolling;
1210 }
1211 
1212 int
1213 xhci_intr(void *v)
1214 {
1215 	struct xhci_softc * const sc = v;
1216 	int ret = 0;
1217 
1218 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1219 
1220 	if (sc == NULL)
1221 		return 0;
1222 
1223 	mutex_spin_enter(&sc->sc_intr_lock);
1224 
1225 	if (sc->sc_dying || !device_has_power(sc->sc_dev))
1226 		goto done;
1227 
1228 	/* If we get an interrupt while polling, then just ignore it. */
1229 	if (xhci_polling_p(sc)) {
1230 #ifdef DIAGNOSTIC
1231 		DPRINTFN(16, "ignored interrupt while polling", 0, 0, 0, 0);
1232 #endif
1233 		goto done;
1234 	}
1235 
1236 	ret = xhci_intr1(sc);
1237 	if (ret) {
1238 		KASSERT(sc->sc_child || sc->sc_child2);
1239 
1240 		/*
1241 		 * One of child busses could be already detached. It doesn't
1242 		 * matter on which of the two the softintr is scheduled.
1243 		 */
1244 		if (sc->sc_child)
1245 			usb_schedsoftintr(&sc->sc_bus);
1246 		else
1247 			usb_schedsoftintr(&sc->sc_bus2);
1248 	}
1249 done:
1250 	mutex_spin_exit(&sc->sc_intr_lock);
1251 	return ret;
1252 }
1253 
1254 int
1255 xhci_intr1(struct xhci_softc * const sc)
1256 {
1257 	uint32_t usbsts;
1258 	uint32_t iman;
1259 
1260 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1261 
1262 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
1263 	DPRINTFN(16, "USBSTS %08jx", usbsts, 0, 0, 0);
1264 	if ((usbsts & (XHCI_STS_HSE | XHCI_STS_EINT | XHCI_STS_PCD |
1265 	    XHCI_STS_HCE)) == 0) {
1266 		DPRINTFN(16, "ignored intr not for %s",
1267 		    device_xname(sc->sc_dev), 0, 0, 0);
1268 		return 0;
1269 	}
1270 
1271 	/*
1272 	 * Clear EINT and other transient flags, to not misenterpret
1273 	 * next shared interrupt. Also, to avoid race, EINT must be cleared
1274 	 * before XHCI_IMAN_INTR_PEND is cleared.
1275 	 */
1276 	xhci_op_write_4(sc, XHCI_USBSTS, usbsts & XHCI_STS_RSVDP0);
1277 
1278 #ifdef XHCI_DEBUG
1279 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
1280 	DPRINTFN(16, "USBSTS %08jx", usbsts, 0, 0, 0);
1281 #endif
1282 
1283 	iman = xhci_rt_read_4(sc, XHCI_IMAN(0));
1284 	DPRINTFN(16, "IMAN0 %08jx", iman, 0, 0, 0);
1285 	iman |= XHCI_IMAN_INTR_PEND;
1286 	xhci_rt_write_4(sc, XHCI_IMAN(0), iman);
1287 
1288 #ifdef XHCI_DEBUG
1289 	iman = xhci_rt_read_4(sc, XHCI_IMAN(0));
1290 	DPRINTFN(16, "IMAN0 %08jx", iman, 0, 0, 0);
1291 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
1292 	DPRINTFN(16, "USBSTS %08jx", usbsts, 0, 0, 0);
1293 #endif
1294 
1295 	return 1;
1296 }
1297 
1298 /*
1299  * 3 port speed types used in USB stack
1300  *
1301  * usbdi speed
1302  *	definition: USB_SPEED_* in usb.h
1303  *	They are used in struct usbd_device in USB stack.
1304  *	ioctl interface uses these values too.
1305  * port_status speed
1306  *	definition: UPS_*_SPEED in usb.h
1307  *	They are used in usb_port_status_t and valid only for USB 2.0.
1308  *	Speed value is always 0 for Super Speed or more, and dwExtPortStatus
1309  *	of usb_port_status_ext_t indicates port speed.
1310  *	Note that some 3.0 values overlap with 2.0 values.
1311  *	(e.g. 0x200 means UPS_POER_POWER_SS in SS and
1312  *	            means UPS_LOW_SPEED in HS.)
1313  *	port status returned from hub also uses these values.
1314  *	On NetBSD UPS_OTHER_SPEED indicates port speed is super speed
1315  *	or more.
1316  * xspeed:
1317  *	definition: Protocol Speed ID (PSI) (xHCI 1.1 7.2.1)
1318  *	They are used in only slot context and PORTSC reg of xhci.
1319  *	The difference between usbdi speed and xspeed is
1320  *	that FS and LS values are swapped.
1321  */
1322 
1323 /* convert usbdi speed to xspeed */
1324 static int
1325 xhci_speed2xspeed(int speed)
1326 {
1327 	switch (speed) {
1328 	case USB_SPEED_LOW:	return 2;
1329 	case USB_SPEED_FULL:	return 1;
1330 	default:		return speed;
1331 	}
1332 }
1333 
1334 #if 0
1335 /* convert xspeed to usbdi speed */
1336 static int
1337 xhci_xspeed2speed(int xspeed)
1338 {
1339 	switch (xspeed) {
1340 	case 1: return USB_SPEED_FULL;
1341 	case 2: return USB_SPEED_LOW;
1342 	default: return xspeed;
1343 	}
1344 }
1345 #endif
1346 
1347 /* convert xspeed to port status speed */
1348 static int
1349 xhci_xspeed2psspeed(int xspeed)
1350 {
1351 	switch (xspeed) {
1352 	case 0: return 0;
1353 	case 1: return UPS_FULL_SPEED;
1354 	case 2: return UPS_LOW_SPEED;
1355 	case 3: return UPS_HIGH_SPEED;
1356 	default: return UPS_OTHER_SPEED;
1357 	}
1358 }
1359 
1360 /*
1361  * Construct input contexts and issue TRB to open pipe.
1362  */
1363 static usbd_status
1364 xhci_configure_endpoint(struct usbd_pipe *pipe)
1365 {
1366 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1367 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1368 #ifdef USB_DEBUG
1369 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
1370 #endif
1371 	struct xhci_trb trb;
1372 	usbd_status err;
1373 
1374 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1375 	DPRINTFN(4, "slot %ju dci %ju epaddr 0x%02jx attr 0x%02jx",
1376 	    xs->xs_idx, dci, pipe->up_endpoint->ue_edesc->bEndpointAddress,
1377 	    pipe->up_endpoint->ue_edesc->bmAttributes);
1378 
1379 	/* XXX ensure input context is available? */
1380 
1381 	memset(xhci_slot_get_icv(sc, xs, 0), 0, sc->sc_pgsz);
1382 
1383 	/* set up context */
1384 	xhci_setup_ctx(pipe);
1385 
1386 	HEXDUMP("input control context", xhci_slot_get_icv(sc, xs, 0),
1387 	    sc->sc_ctxsz * 1);
1388 	HEXDUMP("input endpoint context", xhci_slot_get_icv(sc, xs,
1389 	    xhci_dci_to_ici(dci)), sc->sc_ctxsz * 1);
1390 
1391 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
1392 	trb.trb_2 = 0;
1393 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
1394 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP);
1395 
1396 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
1397 
1398 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
1399 	HEXDUMP("output context", xhci_slot_get_dcv(sc, xs, dci),
1400 	    sc->sc_ctxsz * 1);
1401 
1402 	return err;
1403 }
1404 
1405 #if 0
1406 static usbd_status
1407 xhci_unconfigure_endpoint(struct usbd_pipe *pipe)
1408 {
1409 #ifdef USB_DEBUG
1410 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1411 #endif
1412 
1413 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1414 	DPRINTFN(4, "slot %ju", xs->xs_idx, 0, 0, 0);
1415 
1416 	return USBD_NORMAL_COMPLETION;
1417 }
1418 #endif
1419 
1420 /* 4.6.8, 6.4.3.7 */
1421 static usbd_status
1422 xhci_reset_endpoint_locked(struct usbd_pipe *pipe)
1423 {
1424 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1425 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1426 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
1427 	struct xhci_trb trb;
1428 	usbd_status err;
1429 
1430 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1431 	DPRINTFN(4, "slot %ju dci %ju", xs->xs_idx, dci, 0, 0);
1432 
1433 	KASSERT(mutex_owned(&sc->sc_lock));
1434 
1435 	trb.trb_0 = 0;
1436 	trb.trb_2 = 0;
1437 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
1438 	    XHCI_TRB_3_EP_SET(dci) |
1439 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP);
1440 
1441 	err = xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
1442 
1443 	return err;
1444 }
1445 
1446 static usbd_status
1447 xhci_reset_endpoint(struct usbd_pipe *pipe)
1448 {
1449 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1450 
1451 	mutex_enter(&sc->sc_lock);
1452 	usbd_status ret = xhci_reset_endpoint_locked(pipe);
1453 	mutex_exit(&sc->sc_lock);
1454 
1455 	return ret;
1456 }
1457 
1458 /*
1459  * 4.6.9, 6.4.3.8
1460  * Stop execution of TDs on xfer ring.
1461  * Should be called with sc_lock held.
1462  */
1463 static usbd_status
1464 xhci_stop_endpoint(struct usbd_pipe *pipe)
1465 {
1466 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1467 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1468 	struct xhci_trb trb;
1469 	usbd_status err;
1470 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
1471 
1472 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1473 	DPRINTFN(4, "slot %ju dci %ju", xs->xs_idx, dci, 0, 0);
1474 
1475 	KASSERT(mutex_owned(&sc->sc_lock));
1476 
1477 	trb.trb_0 = 0;
1478 	trb.trb_2 = 0;
1479 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
1480 	    XHCI_TRB_3_EP_SET(dci) |
1481 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP);
1482 
1483 	err = xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
1484 
1485 	return err;
1486 }
1487 
1488 /*
1489  * Set TR Dequeue Pointer.
1490  * xHCI 1.1  4.6.10  6.4.3.9
1491  * Purge all of the TRBs on ring and reinitialize ring.
1492  * Set TR dequeue Pointr to 0 and Cycle State to 1.
1493  * EPSTATE of endpoint must be ERROR or STOPPED, otherwise CONTEXT_STATE
1494  * error will be generated.
1495  */
1496 static usbd_status
1497 xhci_set_dequeue_locked(struct usbd_pipe *pipe)
1498 {
1499 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1500 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1501 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
1502 	struct xhci_ring * const xr = &xs->xs_ep[dci].xe_tr;
1503 	struct xhci_trb trb;
1504 	usbd_status err;
1505 
1506 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1507 	DPRINTFN(4, "slot %ju dci %ju", xs->xs_idx, dci, 0, 0);
1508 
1509 	KASSERT(mutex_owned(&sc->sc_lock));
1510 
1511 	xhci_host_dequeue(xr);
1512 
1513 	/* set DCS */
1514 	trb.trb_0 = xhci_ring_trbp(xr, 0) | 1; /* XXX */
1515 	trb.trb_2 = 0;
1516 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
1517 	    XHCI_TRB_3_EP_SET(dci) |
1518 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE);
1519 
1520 	err = xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
1521 
1522 	return err;
1523 }
1524 
1525 static usbd_status
1526 xhci_set_dequeue(struct usbd_pipe *pipe)
1527 {
1528 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1529 
1530 	mutex_enter(&sc->sc_lock);
1531 	usbd_status ret = xhci_set_dequeue_locked(pipe);
1532 	mutex_exit(&sc->sc_lock);
1533 
1534 	return ret;
1535 }
1536 
1537 /*
1538  * Open new pipe: called from usbd_setup_pipe_flags.
1539  * Fills methods of pipe.
1540  * If pipe is not for ep0, calls configure_endpoint.
1541  */
1542 static usbd_status
1543 xhci_open(struct usbd_pipe *pipe)
1544 {
1545 	struct usbd_device * const dev = pipe->up_dev;
1546 	struct xhci_softc * const sc = XHCI_BUS2SC(dev->ud_bus);
1547 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
1548 	const uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1549 
1550 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1551 	DPRINTFN(1, "addr %jd depth %jd port %jd speed %jd", dev->ud_addr,
1552 	    dev->ud_depth, dev->ud_powersrc->up_portno, dev->ud_speed);
1553 	DPRINTFN(1, " dci %ju type 0x%02jx epaddr 0x%02jx attr 0x%02jx",
1554 	    xhci_ep_get_dci(ed), ed->bDescriptorType, ed->bEndpointAddress,
1555 	    ed->bmAttributes);
1556 	DPRINTFN(1, " mps %ju ival %ju", UGETW(ed->wMaxPacketSize),
1557 	    ed->bInterval, 0, 0);
1558 
1559 	if (sc->sc_dying)
1560 		return USBD_IOERROR;
1561 
1562 	/* Root Hub */
1563 	if (dev->ud_depth == 0 && dev->ud_powersrc->up_portno == 0) {
1564 		switch (ed->bEndpointAddress) {
1565 		case USB_CONTROL_ENDPOINT:
1566 			pipe->up_methods = &roothub_ctrl_methods;
1567 			break;
1568 		case UE_DIR_IN | USBROOTHUB_INTR_ENDPT:
1569 			pipe->up_methods = &xhci_root_intr_methods;
1570 			break;
1571 		default:
1572 			pipe->up_methods = NULL;
1573 			DPRINTFN(0, "bad bEndpointAddress 0x%02jx",
1574 			    ed->bEndpointAddress, 0, 0, 0);
1575 			return USBD_INVAL;
1576 		}
1577 		return USBD_NORMAL_COMPLETION;
1578 	}
1579 
1580 	switch (xfertype) {
1581 	case UE_CONTROL:
1582 		pipe->up_methods = &xhci_device_ctrl_methods;
1583 		break;
1584 	case UE_ISOCHRONOUS:
1585 		pipe->up_methods = &xhci_device_isoc_methods;
1586 		return USBD_INVAL;
1587 		break;
1588 	case UE_BULK:
1589 		pipe->up_methods = &xhci_device_bulk_methods;
1590 		break;
1591 	case UE_INTERRUPT:
1592 		pipe->up_methods = &xhci_device_intr_methods;
1593 		break;
1594 	default:
1595 		return USBD_IOERROR;
1596 		break;
1597 	}
1598 
1599 	if (ed->bEndpointAddress != USB_CONTROL_ENDPOINT)
1600 		return xhci_configure_endpoint(pipe);
1601 
1602 	return USBD_NORMAL_COMPLETION;
1603 }
1604 
1605 /*
1606  * Closes pipe, called from usbd_kill_pipe via close methods.
1607  * If the endpoint to be closed is ep0, disable_slot.
1608  * Should be called with sc_lock held.
1609  */
1610 static void
1611 xhci_close_pipe(struct usbd_pipe *pipe)
1612 {
1613 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
1614 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
1615 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
1616 	const u_int dci = xhci_ep_get_dci(ed);
1617 	struct xhci_trb trb;
1618 	uint32_t *cp;
1619 
1620 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1621 
1622 	if (sc->sc_dying)
1623 		return;
1624 
1625 	/* xs is uninitialized before xhci_init_slot */
1626 	if (xs == NULL || xs->xs_idx == 0)
1627 		return;
1628 
1629 	DPRINTFN(4, "pipe %#jx slot %ju dci %ju", (uintptr_t)pipe, xs->xs_idx,
1630 	    dci, 0);
1631 
1632 	KASSERTMSG(!cpu_intr_p() && !cpu_softintr_p(), "called from intr ctx");
1633 	KASSERT(mutex_owned(&sc->sc_lock));
1634 
1635 	if (pipe->up_dev->ud_depth == 0)
1636 		return;
1637 
1638 	if (dci == XHCI_DCI_EP_CONTROL) {
1639 		DPRINTFN(4, "closing ep0", 0, 0, 0, 0);
1640 		xhci_disable_slot(sc, xs->xs_idx);
1641 		return;
1642 	}
1643 
1644 	if (xhci_get_epstate(sc, xs, dci) != XHCI_EPSTATE_STOPPED)
1645 		(void)xhci_stop_endpoint(pipe);
1646 
1647 	/*
1648 	 * set appropriate bit to be dropped.
1649 	 * don't set DC bit to 1, otherwise all endpoints
1650 	 * would be deconfigured.
1651 	 */
1652 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
1653 	cp[0] = htole32(XHCI_INCTX_0_DROP_MASK(dci));
1654 	cp[1] = htole32(0);
1655 
1656 	/* XXX should be most significant one, not dci? */
1657 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_SLOT));
1658 	cp[0] = htole32(XHCI_SCTX_0_CTX_NUM_SET(dci));
1659 
1660 	/* configure ep context performs an implicit dequeue */
1661 	xhci_host_dequeue(&xs->xs_ep[dci].xe_tr);
1662 
1663 	/* sync input contexts before they are read from memory */
1664 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
1665 
1666 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
1667 	trb.trb_2 = 0;
1668 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
1669 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP);
1670 
1671 	(void)xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
1672 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
1673 }
1674 
1675 /*
1676  * Abort transfer.
1677  * Should be called with sc_lock held.
1678  */
1679 static void
1680 xhci_abort_xfer(struct usbd_xfer *xfer, usbd_status status)
1681 {
1682 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
1683 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
1684 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
1685 
1686 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1687 	DPRINTFN(4, "xfer %#jx pipe %#jx status %jd",
1688 	    (uintptr_t)xfer, (uintptr_t)xfer->ux_pipe, status, 0);
1689 
1690 	KASSERT(mutex_owned(&sc->sc_lock));
1691 
1692 	if (sc->sc_dying) {
1693 		/* If we're dying, just do the software part. */
1694 		DPRINTFN(4, "xfer %#jx dying %ju", (uintptr_t)xfer,
1695 		    xfer->ux_status, 0, 0);
1696 		xfer->ux_status = status;
1697 		callout_stop(&xfer->ux_callout);
1698 		usb_transfer_complete(xfer);
1699 		return;
1700 	}
1701 
1702 	/*
1703 	 * If an abort is already in progress then just wait for it to
1704 	 * complete and return.
1705 	 */
1706 	if (xfer->ux_hcflags & UXFER_ABORTING) {
1707 		DPRINTFN(4, "already aborting", 0, 0, 0, 0);
1708 #ifdef DIAGNOSTIC
1709 		if (status == USBD_TIMEOUT)
1710 			DPRINTFN(4, "TIMEOUT while aborting", 0, 0, 0, 0);
1711 #endif
1712 		/* Override the status which might be USBD_TIMEOUT. */
1713 		xfer->ux_status = status;
1714 		DPRINTFN(4, "xfer %#jx waiting for abort to finish",
1715 		    (uintptr_t)xfer, 0, 0, 0);
1716 		xfer->ux_hcflags |= UXFER_ABORTWAIT;
1717 		while (xfer->ux_hcflags & UXFER_ABORTING)
1718 			cv_wait(&xfer->ux_hccv, &sc->sc_lock);
1719 		return;
1720 	}
1721 	xfer->ux_hcflags |= UXFER_ABORTING;
1722 
1723 	/*
1724 	 * Step 1: Stop xfer timeout timer.
1725 	 */
1726 	xfer->ux_status = status;
1727 	callout_stop(&xfer->ux_callout);
1728 
1729 	/*
1730 	 * Step 2: Stop execution of TD on the ring.
1731 	 */
1732 	switch (xhci_get_epstate(sc, xs, dci)) {
1733 	case XHCI_EPSTATE_HALTED:
1734 		(void)xhci_reset_endpoint_locked(xfer->ux_pipe);
1735 		break;
1736 	case XHCI_EPSTATE_STOPPED:
1737 		break;
1738 	default:
1739 		(void)xhci_stop_endpoint(xfer->ux_pipe);
1740 		break;
1741 	}
1742 #ifdef DIAGNOSTIC
1743 	uint32_t epst = xhci_get_epstate(sc, xs, dci);
1744 	if (epst != XHCI_EPSTATE_STOPPED)
1745 		DPRINTFN(4, "dci %ju not stopped %ju", dci, epst, 0, 0);
1746 #endif
1747 
1748 	/*
1749 	 * Step 3: Remove any vestiges of the xfer from the ring.
1750 	 */
1751 	xhci_set_dequeue_locked(xfer->ux_pipe);
1752 
1753 	/*
1754 	 * Step 4: Notify completion to waiting xfers.
1755 	 */
1756 	int wake = xfer->ux_hcflags & UXFER_ABORTWAIT;
1757 	xfer->ux_hcflags &= ~(UXFER_ABORTING | UXFER_ABORTWAIT);
1758 	usb_transfer_complete(xfer);
1759 	if (wake) {
1760 		cv_broadcast(&xfer->ux_hccv);
1761 	}
1762 	DPRINTFN(14, "end", 0, 0, 0, 0);
1763 
1764 	KASSERT(mutex_owned(&sc->sc_lock));
1765 }
1766 
1767 static void
1768 xhci_host_dequeue(struct xhci_ring * const xr)
1769 {
1770 	/* When dequeueing the controller, update our struct copy too */
1771 	memset(xr->xr_trb, 0, xr->xr_ntrb * XHCI_TRB_SIZE);
1772 	usb_syncmem(&xr->xr_dma, 0, xr->xr_ntrb * XHCI_TRB_SIZE,
1773 	    BUS_DMASYNC_PREWRITE);
1774 	memset(xr->xr_cookies, 0, xr->xr_ntrb * sizeof(*xr->xr_cookies));
1775 
1776 	xr->xr_ep = 0;
1777 	xr->xr_cs = 1;
1778 }
1779 
1780 /*
1781  * Recover STALLed endpoint.
1782  * xHCI 1.1 sect 4.10.2.1
1783  * Issue RESET_EP to recover halt condition and SET_TR_DEQUEUE to remove
1784  * all transfers on transfer ring.
1785  * These are done in thread context asynchronously.
1786  */
1787 static void
1788 xhci_clear_endpoint_stall_async_task(void *cookie)
1789 {
1790 	struct usbd_xfer * const xfer = cookie;
1791 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
1792 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
1793 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
1794 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
1795 
1796 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1797 	DPRINTFN(4, "xfer %#jx slot %ju dci %ju", (uintptr_t)xfer, xs->xs_idx,
1798 	    dci, 0);
1799 
1800 	xhci_reset_endpoint(xfer->ux_pipe);
1801 	xhci_set_dequeue(xfer->ux_pipe);
1802 
1803 	mutex_enter(&sc->sc_lock);
1804 	tr->is_halted = false;
1805 	usb_transfer_complete(xfer);
1806 	mutex_exit(&sc->sc_lock);
1807 	DPRINTFN(4, "ends", 0, 0, 0, 0);
1808 }
1809 
1810 static usbd_status
1811 xhci_clear_endpoint_stall_async(struct usbd_xfer *xfer)
1812 {
1813 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
1814 	struct xhci_pipe * const xp = (struct xhci_pipe *)xfer->ux_pipe;
1815 
1816 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1817 	DPRINTFN(4, "xfer %#jx", (uintptr_t)xfer, 0, 0, 0);
1818 
1819 	if (sc->sc_dying) {
1820 		return USBD_IOERROR;
1821 	}
1822 
1823 	usb_init_task(&xp->xp_async_task,
1824 	    xhci_clear_endpoint_stall_async_task, xfer, USB_TASKQ_MPSAFE);
1825 	usb_add_task(xfer->ux_pipe->up_dev, &xp->xp_async_task, USB_TASKQ_HC);
1826 	DPRINTFN(4, "ends", 0, 0, 0, 0);
1827 
1828 	return USBD_NORMAL_COMPLETION;
1829 }
1830 
1831 /* Process roothub port status/change events and notify to uhub_intr. */
1832 static void
1833 xhci_rhpsc(struct xhci_softc * const sc, u_int ctlrport)
1834 {
1835 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1836 	DPRINTFN(4, "xhci%jd: port %ju status change", device_unit(sc->sc_dev),
1837 	   ctlrport, 0, 0);
1838 
1839 	if (ctlrport > sc->sc_maxports)
1840 		return;
1841 
1842 	const size_t bn = xhci_ctlrport2bus(sc, ctlrport);
1843 	const size_t rhp = xhci_ctlrport2rhport(sc, ctlrport);
1844 	struct usbd_xfer * const xfer = sc->sc_intrxfer[bn];
1845 
1846 	DPRINTFN(4, "xhci%jd: bus %jd bp %ju xfer %#jx status change",
1847 	    device_unit(sc->sc_dev), bn, rhp, (uintptr_t)xfer);
1848 
1849 	if (xfer == NULL)
1850 		return;
1851 
1852 	uint8_t *p = xfer->ux_buf;
1853 	memset(p, 0, xfer->ux_length);
1854 	p[rhp / NBBY] |= 1 << (rhp % NBBY);
1855 	xfer->ux_actlen = xfer->ux_length;
1856 	xfer->ux_status = USBD_NORMAL_COMPLETION;
1857 	usb_transfer_complete(xfer);
1858 }
1859 
1860 /* Process Transfer Events */
1861 static void
1862 xhci_event_transfer(struct xhci_softc * const sc,
1863     const struct xhci_trb * const trb)
1864 {
1865 	uint64_t trb_0;
1866 	uint32_t trb_2, trb_3;
1867 	uint8_t trbcode;
1868 	u_int slot, dci;
1869 	struct xhci_slot *xs;
1870 	struct xhci_ring *xr;
1871 	struct xhci_xfer *xx;
1872 	struct usbd_xfer *xfer;
1873 	usbd_status err;
1874 
1875 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
1876 
1877 	trb_0 = le64toh(trb->trb_0);
1878 	trb_2 = le32toh(trb->trb_2);
1879 	trb_3 = le32toh(trb->trb_3);
1880 	trbcode = XHCI_TRB_2_ERROR_GET(trb_2);
1881 	slot = XHCI_TRB_3_SLOT_GET(trb_3);
1882 	dci = XHCI_TRB_3_EP_GET(trb_3);
1883 	xs = &sc->sc_slots[slot];
1884 	xr = &xs->xs_ep[dci].xe_tr;
1885 
1886 	/* sanity check */
1887 	KASSERTMSG(xs->xs_idx != 0 && xs->xs_idx <= sc->sc_maxslots,
1888 	    "invalid xs_idx %u slot %u", xs->xs_idx, slot);
1889 
1890 	int idx = 0;
1891 	if ((trb_3 & XHCI_TRB_3_ED_BIT) == 0) {
1892 		if (xhci_trb_get_idx(xr, trb_0, &idx)) {
1893 			DPRINTFN(0, "invalid trb_0 0x%jx", trb_0, 0, 0, 0);
1894 			return;
1895 		}
1896 		xx = xr->xr_cookies[idx];
1897 
1898 		/* clear cookie of consumed TRB */
1899 		xr->xr_cookies[idx] = NULL;
1900 
1901 		/*
1902 		 * xx is NULL if pipe is opened but xfer is not started.
1903 		 * It happens when stopping idle pipe.
1904 		 */
1905 		if (xx == NULL || trbcode == XHCI_TRB_ERROR_LENGTH) {
1906 			DPRINTFN(1, "Ignore #%ju: cookie %#jx cc %ju dci %ju",
1907 			    idx, (uintptr_t)xx, trbcode, dci);
1908 			DPRINTFN(1, " orig TRB %jx type %ju", trb_0,
1909 			    XHCI_TRB_3_TYPE_GET(le32toh(xr->xr_trb[idx].trb_3)),
1910 			    0, 0);
1911 			return;
1912 		}
1913 	} else {
1914 		/* When ED != 0, trb_0 is virtual addr of struct xhci_xfer. */
1915 		xx = (void *)(uintptr_t)(trb_0 & ~0x3);
1916 	}
1917 	/* XXX this may not happen */
1918 	if (xx == NULL) {
1919 		DPRINTFN(1, "xfer done: xx is NULL", 0, 0, 0, 0);
1920 		return;
1921 	}
1922 	xfer = &xx->xx_xfer;
1923 	/* XXX this may happen when detaching */
1924 	if (xfer == NULL) {
1925 		DPRINTFN(1, "xx(%#jx)->xx_xfer is NULL trb_0 %#jx",
1926 		    (uintptr_t)xx, trb_0, 0, 0);
1927 		return;
1928 	}
1929 	DPRINTFN(14, "xfer %#jx", (uintptr_t)xfer, 0, 0, 0);
1930 	/* XXX I dunno why this happens */
1931 	KASSERTMSG(xfer->ux_pipe != NULL, "xfer(%p)->ux_pipe is NULL", xfer);
1932 
1933 	if (!xfer->ux_pipe->up_repeat &&
1934 	    SIMPLEQ_EMPTY(&xfer->ux_pipe->up_queue)) {
1935 		DPRINTFN(1, "xfer(%#jx)->pipe not queued", (uintptr_t)xfer,
1936 		    0, 0, 0);
1937 		return;
1938 	}
1939 
1940 	/* 4.11.5.2 Event Data TRB */
1941 	if ((trb_3 & XHCI_TRB_3_ED_BIT) != 0) {
1942 		DPRINTFN(14, "transfer Event Data: 0x%016jx 0x%08jx"
1943 		    " %02jx", trb_0, XHCI_TRB_2_REM_GET(trb_2), trbcode, 0);
1944 		if ((trb_0 & 0x3) == 0x3) {
1945 			xfer->ux_actlen = XHCI_TRB_2_REM_GET(trb_2);
1946 		}
1947 	}
1948 
1949 	switch (trbcode) {
1950 	case XHCI_TRB_ERROR_SHORT_PKT:
1951 	case XHCI_TRB_ERROR_SUCCESS:
1952 		/*
1953 		 * A ctrl transfer can generate two events if it has a Data
1954 		 * stage.  A short data stage can be OK and should not
1955 		 * complete the transfer as the status stage needs to be
1956 		 * performed.
1957 		 *
1958 		 * Note: Data and Status stage events point at same xfer.
1959 		 * ux_actlen and ux_dmabuf will be passed to
1960 		 * usb_transfer_complete after the Status stage event.
1961 		 *
1962 		 * It can be distingished which stage generates the event:
1963 		 * + by checking least 3 bits of trb_0 if ED==1.
1964 		 *   (see xhci_device_ctrl_start).
1965 		 * + by checking the type of original TRB if ED==0.
1966 		 *
1967 		 * In addition, intr, bulk, and isoc transfer currently
1968 		 * consists of single TD, so the "skip" is not needed.
1969 		 * ctrl xfer uses EVENT_DATA, and others do not.
1970 		 * Thus driver can switch the flow by checking ED bit.
1971 		 */
1972 		if ((trb_3 & XHCI_TRB_3_ED_BIT) == 0) {
1973 			if (xfer->ux_actlen == 0)
1974 				xfer->ux_actlen = xfer->ux_length -
1975 				    XHCI_TRB_2_REM_GET(trb_2);
1976 			if (XHCI_TRB_3_TYPE_GET(le32toh(xr->xr_trb[idx].trb_3))
1977 			    == XHCI_TRB_TYPE_DATA_STAGE) {
1978 				return;
1979 			}
1980 		} else if ((trb_0 & 0x3) == 0x3) {
1981 			return;
1982 		}
1983 		err = USBD_NORMAL_COMPLETION;
1984 		break;
1985 	case XHCI_TRB_ERROR_STOPPED:
1986 	case XHCI_TRB_ERROR_LENGTH:
1987 	case XHCI_TRB_ERROR_STOPPED_SHORT:
1988 		/*
1989 		 * don't complete the transfer being aborted
1990 		 * as abort_xfer does instead.
1991 		 */
1992 		if (xfer->ux_hcflags & UXFER_ABORTING) {
1993 			DPRINTFN(14, "ignore aborting xfer %#jx",
1994 			    (uintptr_t)xfer, 0, 0, 0);
1995 			return;
1996 		}
1997 		err = USBD_CANCELLED;
1998 		break;
1999 	case XHCI_TRB_ERROR_STALL:
2000 	case XHCI_TRB_ERROR_BABBLE:
2001 		DPRINTFN(1, "ERR %ju slot %ju dci %ju", trbcode, slot, dci, 0);
2002 		xr->is_halted = true;
2003 		err = USBD_STALLED;
2004 		/*
2005 		 * Stalled endpoints can be recoverd by issuing
2006 		 * command TRB TYPE_RESET_EP on xHCI instead of
2007 		 * issuing request CLEAR_FEATURE UF_ENDPOINT_HALT
2008 		 * on the endpoint. However, this function may be
2009 		 * called from softint context (e.g. from umass),
2010 		 * in that case driver gets KASSERT in cv_timedwait
2011 		 * in xhci_do_command.
2012 		 * To avoid this, this runs reset_endpoint and
2013 		 * usb_transfer_complete in usb task thread
2014 		 * asynchronously (and then umass issues clear
2015 		 * UF_ENDPOINT_HALT).
2016 		 */
2017 		xfer->ux_status = err;
2018 		callout_stop(&xfer->ux_callout);
2019 		xhci_clear_endpoint_stall_async(xfer);
2020 		return;
2021 	default:
2022 		DPRINTFN(1, "ERR %ju slot %ju dci %ju", trbcode, slot, dci, 0);
2023 		err = USBD_IOERROR;
2024 		break;
2025 	}
2026 	xfer->ux_status = err;
2027 
2028 	if ((trb_3 & XHCI_TRB_3_ED_BIT) != 0) {
2029 		if ((trb_0 & 0x3) == 0x0) {
2030 			callout_stop(&xfer->ux_callout);
2031 			usb_transfer_complete(xfer);
2032 		}
2033 	} else {
2034 		callout_stop(&xfer->ux_callout);
2035 		usb_transfer_complete(xfer);
2036 	}
2037 }
2038 
2039 /* Process Command complete events */
2040 static void
2041 xhci_event_cmd(struct xhci_softc * const sc, const struct xhci_trb * const trb)
2042 {
2043 	uint64_t trb_0;
2044 	uint32_t trb_2, trb_3;
2045 
2046 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2047 
2048 	KASSERT(mutex_owned(&sc->sc_lock));
2049 
2050 	trb_0 = le64toh(trb->trb_0);
2051 	trb_2 = le32toh(trb->trb_2);
2052 	trb_3 = le32toh(trb->trb_3);
2053 
2054 	if (trb_0 == sc->sc_command_addr) {
2055 		sc->sc_resultpending = false;
2056 
2057 		sc->sc_result_trb.trb_0 = trb_0;
2058 		sc->sc_result_trb.trb_2 = trb_2;
2059 		sc->sc_result_trb.trb_3 = trb_3;
2060 		if (XHCI_TRB_2_ERROR_GET(trb_2) !=
2061 		    XHCI_TRB_ERROR_SUCCESS) {
2062 			DPRINTFN(1, "command completion "
2063 			    "failure: 0x%016jx 0x%08jx 0x%08jx",
2064 			    trb_0, trb_2, trb_3, 0);
2065 		}
2066 		cv_signal(&sc->sc_command_cv);
2067 	} else {
2068 		DPRINTFN(1, "spurious event: %#jx 0x%016jx "
2069 		    "0x%08jx 0x%08jx", (uintptr_t)trb, trb_0, trb_2, trb_3);
2070 	}
2071 }
2072 
2073 /*
2074  * Process events.
2075  * called from xhci_softintr
2076  */
2077 static void
2078 xhci_handle_event(struct xhci_softc * const sc,
2079     const struct xhci_trb * const trb)
2080 {
2081 	uint64_t trb_0;
2082 	uint32_t trb_2, trb_3;
2083 
2084 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2085 
2086 	trb_0 = le64toh(trb->trb_0);
2087 	trb_2 = le32toh(trb->trb_2);
2088 	trb_3 = le32toh(trb->trb_3);
2089 
2090 	DPRINTFN(14, "event: %#jx 0x%016jx 0x%08jx 0x%08jx",
2091 	    (uintptr_t)trb, trb_0, trb_2, trb_3);
2092 
2093 	/*
2094 	 * 4.11.3.1, 6.4.2.1
2095 	 * TRB Pointer is invalid for these completion codes.
2096 	 */
2097 	switch (XHCI_TRB_2_ERROR_GET(trb_2)) {
2098 	case XHCI_TRB_ERROR_RING_UNDERRUN:
2099 	case XHCI_TRB_ERROR_RING_OVERRUN:
2100 	case XHCI_TRB_ERROR_VF_RING_FULL:
2101 		return;
2102 	default:
2103 		if (trb_0 == 0) {
2104 			return;
2105 		}
2106 		break;
2107 	}
2108 
2109 	switch (XHCI_TRB_3_TYPE_GET(trb_3)) {
2110 	case XHCI_TRB_EVENT_TRANSFER:
2111 		xhci_event_transfer(sc, trb);
2112 		break;
2113 	case XHCI_TRB_EVENT_CMD_COMPLETE:
2114 		xhci_event_cmd(sc, trb);
2115 		break;
2116 	case XHCI_TRB_EVENT_PORT_STS_CHANGE:
2117 		xhci_rhpsc(sc, (uint32_t)((trb_0 >> 24) & 0xff));
2118 		break;
2119 	default:
2120 		break;
2121 	}
2122 }
2123 
2124 static void
2125 xhci_softintr(void *v)
2126 {
2127 	struct usbd_bus * const bus = v;
2128 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2129 	struct xhci_ring * const er = &sc->sc_er;
2130 	struct xhci_trb *trb;
2131 	int i, j, k;
2132 
2133 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2134 
2135 	KASSERT(xhci_polling_p(sc) || mutex_owned(&sc->sc_lock));
2136 
2137 	i = er->xr_ep;
2138 	j = er->xr_cs;
2139 
2140 	DPRINTFN(16, "er: xr_ep %jd xr_cs %jd", i, j, 0, 0);
2141 
2142 	while (1) {
2143 		usb_syncmem(&er->xr_dma, XHCI_TRB_SIZE * i, XHCI_TRB_SIZE,
2144 		    BUS_DMASYNC_POSTREAD);
2145 		trb = &er->xr_trb[i];
2146 		k = (le32toh(trb->trb_3) & XHCI_TRB_3_CYCLE_BIT) ? 1 : 0;
2147 
2148 		if (j != k)
2149 			break;
2150 
2151 		xhci_handle_event(sc, trb);
2152 
2153 		i++;
2154 		if (i == er->xr_ntrb) {
2155 			i = 0;
2156 			j ^= 1;
2157 		}
2158 	}
2159 
2160 	er->xr_ep = i;
2161 	er->xr_cs = j;
2162 
2163 	xhci_rt_write_8(sc, XHCI_ERDP(0), xhci_ring_trbp(er, er->xr_ep) |
2164 	    XHCI_ERDP_LO_BUSY);
2165 
2166 	DPRINTFN(16, "ends", 0, 0, 0, 0);
2167 
2168 	return;
2169 }
2170 
2171 static void
2172 xhci_poll(struct usbd_bus *bus)
2173 {
2174 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2175 
2176 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2177 
2178 	mutex_enter(&sc->sc_intr_lock);
2179 	int ret = xhci_intr1(sc);
2180 	if (ret) {
2181 		xhci_softintr(bus);
2182 	}
2183 	mutex_exit(&sc->sc_intr_lock);
2184 
2185 	return;
2186 }
2187 
2188 static struct usbd_xfer *
2189 xhci_allocx(struct usbd_bus *bus, unsigned int nframes)
2190 {
2191 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2192 	struct usbd_xfer *xfer;
2193 
2194 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2195 
2196 	xfer = pool_cache_get(sc->sc_xferpool, PR_WAITOK);
2197 	if (xfer != NULL) {
2198 		memset(xfer, 0, sizeof(struct xhci_xfer));
2199 #ifdef DIAGNOSTIC
2200 		xfer->ux_state = XFER_BUSY;
2201 #endif
2202 	}
2203 
2204 	return xfer;
2205 }
2206 
2207 static void
2208 xhci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
2209 {
2210 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2211 
2212 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2213 
2214 #ifdef DIAGNOSTIC
2215 	if (xfer->ux_state != XFER_BUSY) {
2216 		DPRINTFN(0, "xfer=%#jx not busy, 0x%08jx",
2217 		    (uintptr_t)xfer, xfer->ux_state, 0, 0);
2218 	}
2219 	xfer->ux_state = XFER_FREE;
2220 #endif
2221 	pool_cache_put(sc->sc_xferpool, xfer);
2222 }
2223 
2224 static void
2225 xhci_get_lock(struct usbd_bus *bus, kmutex_t **lock)
2226 {
2227 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2228 
2229 	*lock = &sc->sc_lock;
2230 }
2231 
2232 extern uint32_t usb_cookie_no;
2233 
2234 /*
2235  * xHCI 4.3
2236  * Called when uhub_explore finds a new device (via usbd_new_device).
2237  * Port initialization and speed detection (4.3.1) are already done in uhub.c.
2238  * This function does:
2239  *   Allocate and construct dev structure of default endpoint (ep0).
2240  *   Allocate and open pipe of ep0.
2241  *   Enable slot and initialize slot context.
2242  *   Set Address.
2243  *   Read initial device descriptor.
2244  *   Determine initial MaxPacketSize (mps) by speed.
2245  *   Read full device descriptor.
2246  *   Register this device.
2247  * Finally state of device transitions ADDRESSED.
2248  */
2249 static usbd_status
2250 xhci_new_device(device_t parent, struct usbd_bus *bus, int depth,
2251     int speed, int port, struct usbd_port *up)
2252 {
2253 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
2254 	struct usbd_device *dev;
2255 	usbd_status err;
2256 	usb_device_descriptor_t *dd;
2257 	struct xhci_slot *xs;
2258 	uint32_t *cp;
2259 
2260 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2261 	DPRINTFN(4, "port %ju depth %ju speed %ju up %#jx",
2262 	    port, depth, speed, (uintptr_t)up);
2263 
2264 	dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
2265 	dev->ud_bus = bus;
2266 	dev->ud_quirks = &usbd_no_quirk;
2267 	dev->ud_addr = 0;
2268 	dev->ud_ddesc.bMaxPacketSize = 0;
2269 	dev->ud_depth = depth;
2270 	dev->ud_powersrc = up;
2271 	dev->ud_myhub = up->up_parent;
2272 	dev->ud_speed = speed;
2273 	dev->ud_langid = USBD_NOLANG;
2274 	dev->ud_cookie.cookie = ++usb_cookie_no;
2275 
2276 	/* Set up default endpoint handle. */
2277 	dev->ud_ep0.ue_edesc = &dev->ud_ep0desc;
2278 	/* doesn't matter, just don't let it uninitialized */
2279 	dev->ud_ep0.ue_toggle = 0;
2280 
2281 	/* Set up default endpoint descriptor. */
2282 	dev->ud_ep0desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
2283 	dev->ud_ep0desc.bDescriptorType = UDESC_ENDPOINT;
2284 	dev->ud_ep0desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
2285 	dev->ud_ep0desc.bmAttributes = UE_CONTROL;
2286 	dev->ud_ep0desc.bInterval = 0;
2287 
2288 	/* 4.3,  4.8.2.1 */
2289 	switch (speed) {
2290 	case USB_SPEED_SUPER:
2291 	case USB_SPEED_SUPER_PLUS:
2292 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_3_MAX_CTRL_PACKET);
2293 		break;
2294 	case USB_SPEED_FULL:
2295 		/* XXX using 64 as initial mps of ep0 in FS */
2296 	case USB_SPEED_HIGH:
2297 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_2_MAX_CTRL_PACKET);
2298 		break;
2299 	case USB_SPEED_LOW:
2300 	default:
2301 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_MAX_IPACKET);
2302 		break;
2303 	}
2304 
2305 	up->up_dev = dev;
2306 
2307 	/* Establish the default pipe. */
2308 	err = usbd_setup_pipe(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
2309 	    &dev->ud_pipe0);
2310 	if (err) {
2311 		goto bad;
2312 	}
2313 
2314 	dd = &dev->ud_ddesc;
2315 
2316 	if (depth == 0 && port == 0) {
2317 		KASSERT(bus->ub_devices[USB_ROOTHUB_INDEX] == NULL);
2318 		bus->ub_devices[USB_ROOTHUB_INDEX] = dev;
2319 		err = usbd_get_initial_ddesc(dev, dd);
2320 		if (err) {
2321 			DPRINTFN(1, "get_initial_ddesc %ju", err, 0, 0, 0);
2322 			goto bad;
2323 		}
2324 
2325 		err = usbd_reload_device_desc(dev);
2326 		if (err) {
2327 			DPRINTFN(1, "reload desc %ju", err, 0, 0, 0);
2328 			goto bad;
2329 		}
2330 	} else {
2331 		uint8_t slot = 0;
2332 
2333 		/* 4.3.2 */
2334 		err = xhci_enable_slot(sc, &slot);
2335 		if (err) {
2336 			DPRINTFN(1, "enable slot %ju", err, 0, 0, 0);
2337 			goto bad;
2338 		}
2339 
2340 		xs = &sc->sc_slots[slot];
2341 		dev->ud_hcpriv = xs;
2342 
2343 		/* 4.3.3 initialize slot structure */
2344 		err = xhci_init_slot(dev, slot);
2345 		if (err) {
2346 			DPRINTFN(1, "init slot %ju", err, 0, 0, 0);
2347 			dev->ud_hcpriv = NULL;
2348 			/*
2349 			 * We have to disable_slot here because
2350 			 * xs->xs_idx == 0 when xhci_init_slot fails,
2351 			 * in that case usbd_remove_dev won't work.
2352 			 */
2353 			mutex_enter(&sc->sc_lock);
2354 			xhci_disable_slot(sc, slot);
2355 			mutex_exit(&sc->sc_lock);
2356 			goto bad;
2357 		}
2358 
2359 		/* 4.3.4 Address Assignment */
2360 		err = xhci_set_address(dev, slot, false);
2361 		if (err) {
2362 			DPRINTFN(1, "set address w/o bsr %ju", err, 0, 0, 0);
2363 			goto bad;
2364 		}
2365 
2366 		/* Allow device time to set new address */
2367 		usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
2368 
2369 		usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
2370 		cp = xhci_slot_get_dcv(sc, xs, XHCI_DCI_SLOT);
2371 		HEXDUMP("slot context", cp, sc->sc_ctxsz);
2372 		uint8_t addr = XHCI_SCTX_3_DEV_ADDR_GET(le32toh(cp[3]));
2373 		DPRINTFN(4, "device address %ju", addr, 0, 0, 0);
2374 		/*
2375 		 * XXX ensure we know when the hardware does something
2376 		 * we can't yet cope with
2377 		 */
2378 		KASSERTMSG(addr >= 1 && addr <= 127, "addr %d", addr);
2379 		dev->ud_addr = addr;
2380 
2381 		KASSERTMSG(bus->ub_devices[usb_addr2dindex(dev->ud_addr)] == NULL,
2382 		    "addr %d already allocated", dev->ud_addr);
2383 		/*
2384 		 * The root hub is given its own slot
2385 		 */
2386 		bus->ub_devices[usb_addr2dindex(dev->ud_addr)] = dev;
2387 
2388 		err = usbd_get_initial_ddesc(dev, dd);
2389 		if (err) {
2390 			DPRINTFN(1, "get_initial_ddesc %ju", err, 0, 0, 0);
2391 			goto bad;
2392 		}
2393 
2394 		/* 4.8.2.1 */
2395 		if (USB_IS_SS(speed)) {
2396 			if (dd->bMaxPacketSize != 9) {
2397 				printf("%s: invalid mps 2^%u for SS ep0,"
2398 				    " using 512\n",
2399 				    device_xname(sc->sc_dev),
2400 				    dd->bMaxPacketSize);
2401 				dd->bMaxPacketSize = 9;
2402 			}
2403 			USETW(dev->ud_ep0desc.wMaxPacketSize,
2404 			    (1 << dd->bMaxPacketSize));
2405 		} else
2406 			USETW(dev->ud_ep0desc.wMaxPacketSize,
2407 			    dd->bMaxPacketSize);
2408 		DPRINTFN(4, "bMaxPacketSize %ju", dd->bMaxPacketSize, 0, 0, 0);
2409 		err = xhci_update_ep0_mps(sc, xs,
2410 		    UGETW(dev->ud_ep0desc.wMaxPacketSize));
2411 		if (err) {
2412 			DPRINTFN(1, "update mps of ep0 %ju", err, 0, 0, 0);
2413 			goto bad;
2414 		}
2415 
2416 		err = usbd_reload_device_desc(dev);
2417 		if (err) {
2418 			DPRINTFN(1, "reload desc %ju", err, 0, 0, 0);
2419 			goto bad;
2420 		}
2421 	}
2422 
2423 	DPRINTFN(1, "adding unit addr=%jd, rev=%02jx,",
2424 		dev->ud_addr, UGETW(dd->bcdUSB), 0, 0);
2425 	DPRINTFN(1, " class=%jd, subclass=%jd, protocol=%jd,",
2426 		dd->bDeviceClass, dd->bDeviceSubClass,
2427 		dd->bDeviceProtocol, 0);
2428 	DPRINTFN(1, " mps=%jd, len=%jd, noconf=%jd, speed=%jd",
2429 		dd->bMaxPacketSize, dd->bLength, dd->bNumConfigurations,
2430 		dev->ud_speed);
2431 
2432 	usbd_get_device_strings(dev);
2433 
2434 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
2435 
2436 	if (depth == 0 && port == 0) {
2437 		usbd_attach_roothub(parent, dev);
2438 		DPRINTFN(1, "root hub %#jx", (uintptr_t)dev, 0, 0, 0);
2439 		return USBD_NORMAL_COMPLETION;
2440 	}
2441 
2442 	err = usbd_probe_and_attach(parent, dev, port, dev->ud_addr);
2443  bad:
2444 	if (err != USBD_NORMAL_COMPLETION) {
2445 		usbd_remove_device(dev, up);
2446 	}
2447 
2448 	return err;
2449 }
2450 
2451 static usbd_status
2452 xhci_ring_init(struct xhci_softc * const sc, struct xhci_ring * const xr,
2453     size_t ntrb, size_t align)
2454 {
2455 	usbd_status err;
2456 	size_t size = ntrb * XHCI_TRB_SIZE;
2457 
2458 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2459 
2460 	err = usb_allocmem(&sc->sc_bus, size, align, &xr->xr_dma);
2461 	if (err)
2462 		return err;
2463 	mutex_init(&xr->xr_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
2464 	xr->xr_cookies = kmem_zalloc(sizeof(*xr->xr_cookies) * ntrb, KM_SLEEP);
2465 	xr->xr_trb = xhci_ring_trbv(xr, 0);
2466 	xr->xr_ntrb = ntrb;
2467 	xr->is_halted = false;
2468 	xhci_host_dequeue(xr);
2469 
2470 	return USBD_NORMAL_COMPLETION;
2471 }
2472 
2473 static void
2474 xhci_ring_free(struct xhci_softc * const sc, struct xhci_ring * const xr)
2475 {
2476 	usb_freemem(&sc->sc_bus, &xr->xr_dma);
2477 	mutex_destroy(&xr->xr_lock);
2478 	kmem_free(xr->xr_cookies, sizeof(*xr->xr_cookies) * xr->xr_ntrb);
2479 }
2480 
2481 static void
2482 xhci_ring_put(struct xhci_softc * const sc, struct xhci_ring * const xr,
2483     void *cookie, struct xhci_trb * const trbs, size_t ntrbs)
2484 {
2485 	size_t i;
2486 	u_int ri;
2487 	u_int cs;
2488 	uint64_t parameter;
2489 	uint32_t status;
2490 	uint32_t control;
2491 
2492 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2493 
2494 	KASSERTMSG(ntrbs <= XHCI_XFER_NTRB, "ntrbs %zu", ntrbs);
2495 	for (i = 0; i < ntrbs; i++) {
2496 		DPRINTFN(12, "xr %#jx trbs %#jx num %ju", (uintptr_t)xr,
2497 		    (uintptr_t)trbs, i, 0);
2498 		DPRINTFN(12, " %016jx %08jx %08jx",
2499 		    trbs[i].trb_0, trbs[i].trb_2, trbs[i].trb_3, 0);
2500 		KASSERTMSG(XHCI_TRB_3_TYPE_GET(trbs[i].trb_3) !=
2501 		    XHCI_TRB_TYPE_LINK, "trbs[%zu].trb3 %#x", i, trbs[i].trb_3);
2502 	}
2503 
2504 	DPRINTFN(12, "%#jx xr_ep 0x%jx xr_cs %ju", (uintptr_t)xr, xr->xr_ep,
2505 	    xr->xr_cs, 0);
2506 
2507 	ri = xr->xr_ep;
2508 	cs = xr->xr_cs;
2509 
2510 	/*
2511 	 * Although the xhci hardware can do scatter/gather dma from
2512 	 * arbitrary sized buffers, there is a non-obvious restriction
2513 	 * that a LINK trb is only allowed at the end of a burst of
2514 	 * transfers - which might be 16kB.
2515 	 * Arbitrary aligned LINK trb definitely fail on Ivy bridge.
2516 	 * The simple solution is not to allow a LINK trb in the middle
2517 	 * of anything - as here.
2518 	 * XXX: (dsl) There are xhci controllers out there (eg some made by
2519 	 * ASMedia) that seem to lock up if they process a LINK trb but
2520 	 * cannot process the linked-to trb yet.
2521 	 * The code should write the 'cycle' bit on the link trb AFTER
2522 	 * adding the other trb.
2523 	 */
2524 	u_int firstep = xr->xr_ep;
2525 	u_int firstcs = xr->xr_cs;
2526 
2527 	for (i = 0; i < ntrbs; ) {
2528 		u_int oldri = ri;
2529 		u_int oldcs = cs;
2530 
2531 		if (ri >= (xr->xr_ntrb - 1)) {
2532 			/* Put Link TD at the end of ring */
2533 			parameter = xhci_ring_trbp(xr, 0);
2534 			status = 0;
2535 			control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
2536 			    XHCI_TRB_3_TC_BIT;
2537 			xr->xr_cookies[ri] = NULL;
2538 			xr->xr_ep = 0;
2539 			xr->xr_cs ^= 1;
2540 			ri = xr->xr_ep;
2541 			cs = xr->xr_cs;
2542 		} else {
2543 			parameter = trbs[i].trb_0;
2544 			status = trbs[i].trb_2;
2545 			control = trbs[i].trb_3;
2546 
2547 			xr->xr_cookies[ri] = cookie;
2548 			ri++;
2549 			i++;
2550 		}
2551 		/*
2552 		 * If this is a first TRB, mark it invalid to prevent
2553 		 * xHC from running it immediately.
2554 		 */
2555 		if (oldri == firstep) {
2556 			if (oldcs) {
2557 				control &= ~XHCI_TRB_3_CYCLE_BIT;
2558 			} else {
2559 				control |= XHCI_TRB_3_CYCLE_BIT;
2560 			}
2561 		} else {
2562 			if (oldcs) {
2563 				control |= XHCI_TRB_3_CYCLE_BIT;
2564 			} else {
2565 				control &= ~XHCI_TRB_3_CYCLE_BIT;
2566 			}
2567 		}
2568 		xhci_trb_put(&xr->xr_trb[oldri], parameter, status, control);
2569 		usb_syncmem(&xr->xr_dma, XHCI_TRB_SIZE * oldri,
2570 		    XHCI_TRB_SIZE * 1, BUS_DMASYNC_PREWRITE);
2571 	}
2572 
2573 	/* Now invert cycle bit of first TRB */
2574 	if (firstcs) {
2575 		xr->xr_trb[firstep].trb_3 |= htole32(XHCI_TRB_3_CYCLE_BIT);
2576 	} else {
2577 		xr->xr_trb[firstep].trb_3 &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
2578 	}
2579 	usb_syncmem(&xr->xr_dma, XHCI_TRB_SIZE * firstep,
2580 	    XHCI_TRB_SIZE * 1, BUS_DMASYNC_PREWRITE);
2581 
2582 	xr->xr_ep = ri;
2583 	xr->xr_cs = cs;
2584 
2585 	DPRINTFN(12, "%#jx xr_ep 0x%jx xr_cs %ju", (uintptr_t)xr, xr->xr_ep,
2586 	    xr->xr_cs, 0);
2587 }
2588 
2589 /*
2590  * Stop execution commands, purge all commands on command ring, and
2591  * rewind dequeue pointer.
2592  */
2593 static void
2594 xhci_abort_command(struct xhci_softc *sc)
2595 {
2596 	struct xhci_ring * const cr = &sc->sc_cr;
2597 	uint64_t crcr;
2598 	int i;
2599 
2600 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2601 	DPRINTFN(14, "command %#jx timeout, aborting",
2602 	    sc->sc_command_addr, 0, 0, 0);
2603 
2604 	mutex_enter(&cr->xr_lock);
2605 
2606 	/* 4.6.1.2 Aborting a Command */
2607 	crcr = xhci_op_read_8(sc, XHCI_CRCR);
2608 	xhci_op_write_8(sc, XHCI_CRCR, crcr | XHCI_CRCR_LO_CA);
2609 
2610 	for (i = 0; i < 500; i++) {
2611 		crcr = xhci_op_read_8(sc, XHCI_CRCR);
2612 		if ((crcr & XHCI_CRCR_LO_CRR) == 0)
2613 			break;
2614 		usb_delay_ms(&sc->sc_bus, 1);
2615 	}
2616 	if ((crcr & XHCI_CRCR_LO_CRR) != 0) {
2617 		DPRINTFN(1, "Command Abort timeout", 0, 0, 0, 0);
2618 		/* reset HC here? */
2619 	}
2620 
2621 	/* reset command ring dequeue pointer */
2622 	cr->xr_ep = 0;
2623 	cr->xr_cs = 1;
2624 	xhci_op_write_8(sc, XHCI_CRCR, xhci_ring_trbp(cr, 0) | cr->xr_cs);
2625 
2626 	mutex_exit(&cr->xr_lock);
2627 }
2628 
2629 /*
2630  * Put a command on command ring, ring bell, set timer, and cv_timedwait.
2631  * Command completion is notified by cv_signal from xhci_event_cmd()
2632  * (called from xhci_softint), or timed-out.
2633  * The completion code is copied to sc->sc_result_trb in xhci_event_cmd(),
2634  * then do_command examines it.
2635  */
2636 static usbd_status
2637 xhci_do_command_locked(struct xhci_softc * const sc,
2638     struct xhci_trb * const trb, int timeout)
2639 {
2640 	struct xhci_ring * const cr = &sc->sc_cr;
2641 	usbd_status err;
2642 
2643 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2644 	DPRINTFN(12, "input: 0x%016jx 0x%08jx 0x%08jx",
2645 	    trb->trb_0, trb->trb_2, trb->trb_3, 0);
2646 
2647 	KASSERTMSG(!cpu_intr_p() && !cpu_softintr_p(), "called from intr ctx");
2648 	KASSERT(mutex_owned(&sc->sc_lock));
2649 
2650 	while (sc->sc_command_addr != 0)
2651 		cv_wait(&sc->sc_cmdbusy_cv, &sc->sc_lock);
2652 
2653 	/*
2654 	 * If enqueue pointer points at last of ring, it's Link TRB,
2655 	 * command TRB will be stored in 0th TRB.
2656 	 */
2657 	if (cr->xr_ep == cr->xr_ntrb - 1)
2658 		sc->sc_command_addr = xhci_ring_trbp(cr, 0);
2659 	else
2660 		sc->sc_command_addr = xhci_ring_trbp(cr, cr->xr_ep);
2661 
2662 	sc->sc_resultpending = true;
2663 
2664 	mutex_enter(&cr->xr_lock);
2665 	xhci_ring_put(sc, cr, NULL, trb, 1);
2666 	mutex_exit(&cr->xr_lock);
2667 
2668 	xhci_db_write_4(sc, XHCI_DOORBELL(0), 0);
2669 
2670 	while (sc->sc_resultpending) {
2671 		if (cv_timedwait(&sc->sc_command_cv, &sc->sc_lock,
2672 		    MAX(1, mstohz(timeout))) == EWOULDBLOCK) {
2673 			xhci_abort_command(sc);
2674 			err = USBD_TIMEOUT;
2675 			goto timedout;
2676 		}
2677 	}
2678 
2679 	trb->trb_0 = sc->sc_result_trb.trb_0;
2680 	trb->trb_2 = sc->sc_result_trb.trb_2;
2681 	trb->trb_3 = sc->sc_result_trb.trb_3;
2682 
2683 	DPRINTFN(12, "output: 0x%016jx 0x%08jx 0x%08jx",
2684 	    trb->trb_0, trb->trb_2, trb->trb_3, 0);
2685 
2686 	switch (XHCI_TRB_2_ERROR_GET(trb->trb_2)) {
2687 	case XHCI_TRB_ERROR_SUCCESS:
2688 		err = USBD_NORMAL_COMPLETION;
2689 		break;
2690 	default:
2691 	case 192 ... 223:
2692 		err = USBD_IOERROR;
2693 		break;
2694 	case 224 ... 255:
2695 		err = USBD_NORMAL_COMPLETION;
2696 		break;
2697 	}
2698 
2699 timedout:
2700 	sc->sc_resultpending = false;
2701 	sc->sc_command_addr = 0;
2702 	cv_broadcast(&sc->sc_cmdbusy_cv);
2703 
2704 	return err;
2705 }
2706 
2707 static usbd_status
2708 xhci_do_command(struct xhci_softc * const sc, struct xhci_trb * const trb,
2709     int timeout)
2710 {
2711 
2712 	mutex_enter(&sc->sc_lock);
2713 	usbd_status ret = xhci_do_command_locked(sc, trb, timeout);
2714 	mutex_exit(&sc->sc_lock);
2715 
2716 	return ret;
2717 }
2718 
2719 static usbd_status
2720 xhci_enable_slot(struct xhci_softc * const sc, uint8_t * const slotp)
2721 {
2722 	struct xhci_trb trb;
2723 	usbd_status err;
2724 
2725 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2726 
2727 	trb.trb_0 = 0;
2728 	trb.trb_2 = 0;
2729 	trb.trb_3 = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT);
2730 
2731 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
2732 	if (err != USBD_NORMAL_COMPLETION) {
2733 		return err;
2734 	}
2735 
2736 	*slotp = XHCI_TRB_3_SLOT_GET(trb.trb_3);
2737 
2738 	return err;
2739 }
2740 
2741 /*
2742  * xHCI 4.6.4
2743  * Deallocate ring and device/input context DMA buffers, and disable_slot.
2744  * All endpoints in the slot should be stopped.
2745  * Should be called with sc_lock held.
2746  */
2747 static usbd_status
2748 xhci_disable_slot(struct xhci_softc * const sc, uint8_t slot)
2749 {
2750 	struct xhci_trb trb;
2751 	struct xhci_slot *xs;
2752 	usbd_status err;
2753 
2754 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2755 
2756 	if (sc->sc_dying)
2757 		return USBD_IOERROR;
2758 
2759 	trb.trb_0 = 0;
2760 	trb.trb_2 = 0;
2761 	trb.trb_3 = htole32(
2762 		XHCI_TRB_3_SLOT_SET(slot) |
2763 		XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT));
2764 
2765 	err = xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
2766 
2767 	if (!err) {
2768 		xs = &sc->sc_slots[slot];
2769 		if (xs->xs_idx != 0) {
2770 			xhci_free_slot(sc, xs, XHCI_DCI_SLOT + 1, 32);
2771 			xhci_set_dcba(sc, 0, slot);
2772 			memset(xs, 0, sizeof(*xs));
2773 		}
2774 	}
2775 
2776 	return err;
2777 }
2778 
2779 /*
2780  * Set address of device and transition slot state from ENABLED to ADDRESSED
2781  * if Block Setaddress Request (BSR) is false.
2782  * If BSR==true, transition slot state from ENABLED to DEFAULT.
2783  * see xHCI 1.1  4.5.3, 3.3.4
2784  * Should be called without sc_lock held.
2785  */
2786 static usbd_status
2787 xhci_address_device(struct xhci_softc * const sc,
2788     uint64_t icp, uint8_t slot_id, bool bsr)
2789 {
2790 	struct xhci_trb trb;
2791 	usbd_status err;
2792 
2793 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2794 
2795 	trb.trb_0 = icp;
2796 	trb.trb_2 = 0;
2797 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(slot_id) |
2798 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
2799 	    (bsr ? XHCI_TRB_3_BSR_BIT : 0);
2800 
2801 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
2802 
2803 	if (XHCI_TRB_2_ERROR_GET(trb.trb_2) == XHCI_TRB_ERROR_NO_SLOTS)
2804 		err = USBD_NO_ADDR;
2805 
2806 	return err;
2807 }
2808 
2809 static usbd_status
2810 xhci_update_ep0_mps(struct xhci_softc * const sc,
2811     struct xhci_slot * const xs, u_int mps)
2812 {
2813 	struct xhci_trb trb;
2814 	usbd_status err;
2815 	uint32_t * cp;
2816 
2817 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2818 	DPRINTFN(4, "slot %ju mps %ju", xs->xs_idx, mps, 0, 0);
2819 
2820 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
2821 	cp[0] = htole32(0);
2822 	cp[1] = htole32(XHCI_INCTX_1_ADD_MASK(XHCI_DCI_EP_CONTROL));
2823 
2824 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_EP_CONTROL));
2825 	cp[1] = htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
2826 
2827 	/* sync input contexts before they are read from memory */
2828 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
2829 	HEXDUMP("input context", xhci_slot_get_icv(sc, xs, 0),
2830 	    sc->sc_ctxsz * 4);
2831 
2832 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
2833 	trb.trb_2 = 0;
2834 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
2835 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX);
2836 
2837 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
2838 	return err;
2839 }
2840 
2841 static void
2842 xhci_set_dcba(struct xhci_softc * const sc, uint64_t dcba, int si)
2843 {
2844 	uint64_t * const dcbaa = KERNADDR(&sc->sc_dcbaa_dma, 0);
2845 
2846 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2847 	DPRINTFN(4, "dcbaa %#jx dc %016jx slot %jd",
2848 	    (uintptr_t)&dcbaa[si], dcba, si, 0);
2849 
2850 	dcbaa[si] = htole64(dcba);
2851 	usb_syncmem(&sc->sc_dcbaa_dma, si * sizeof(uint64_t), sizeof(uint64_t),
2852 	    BUS_DMASYNC_PREWRITE);
2853 }
2854 
2855 /*
2856  * Allocate device and input context DMA buffer, and
2857  * TRB DMA buffer for each endpoint.
2858  */
2859 static usbd_status
2860 xhci_init_slot(struct usbd_device *dev, uint32_t slot)
2861 {
2862 	struct xhci_softc * const sc = XHCI_BUS2SC(dev->ud_bus);
2863 	struct xhci_slot *xs;
2864 	usbd_status err;
2865 	u_int dci;
2866 
2867 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2868 	DPRINTFN(4, "slot %ju", slot, 0, 0, 0);
2869 
2870 	xs = &sc->sc_slots[slot];
2871 
2872 	/* allocate contexts */
2873 	err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz, sc->sc_pgsz,
2874 	    &xs->xs_dc_dma);
2875 	if (err)
2876 		return err;
2877 	memset(KERNADDR(&xs->xs_dc_dma, 0), 0, sc->sc_pgsz);
2878 
2879 	err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz, sc->sc_pgsz,
2880 	    &xs->xs_ic_dma);
2881 	if (err)
2882 		goto bad1;
2883 	memset(KERNADDR(&xs->xs_ic_dma, 0), 0, sc->sc_pgsz);
2884 
2885 	for (dci = 0; dci < 32; dci++) {
2886 		//CTASSERT(sizeof(xs->xs_ep[dci]) == sizeof(struct xhci_endpoint));
2887 		memset(&xs->xs_ep[dci], 0, sizeof(xs->xs_ep[dci]));
2888 		if (dci == XHCI_DCI_SLOT)
2889 			continue;
2890 		err = xhci_ring_init(sc, &xs->xs_ep[dci].xe_tr,
2891 		    XHCI_TRANSFER_RING_TRBS, XHCI_TRB_ALIGN);
2892 		if (err) {
2893 			DPRINTFN(0, "ring init failure", 0, 0, 0, 0);
2894 			goto bad2;
2895 		}
2896 	}
2897 
2898  bad2:
2899 	if (err == USBD_NORMAL_COMPLETION) {
2900 		xs->xs_idx = slot;
2901 	} else {
2902 		xhci_free_slot(sc, xs, XHCI_DCI_SLOT + 1, dci);
2903 	}
2904 
2905 	return err;
2906 
2907  bad1:
2908 	usb_freemem(&sc->sc_bus, &xs->xs_dc_dma);
2909 	xs->xs_idx = 0;
2910 	return err;
2911 }
2912 
2913 static void
2914 xhci_free_slot(struct xhci_softc *sc, struct xhci_slot *xs, int start_dci,
2915     int end_dci)
2916 {
2917 	u_int dci;
2918 
2919 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2920 	DPRINTFN(4, "slot %ju start %ju end %ju", xs->xs_idx, start_dci,
2921 	    end_dci, 0);
2922 
2923 	for (dci = start_dci; dci < end_dci; dci++) {
2924 		xhci_ring_free(sc, &xs->xs_ep[dci].xe_tr);
2925 		memset(&xs->xs_ep[dci], 0, sizeof(xs->xs_ep[dci]));
2926 	}
2927 	usb_freemem(&sc->sc_bus, &xs->xs_ic_dma);
2928 	usb_freemem(&sc->sc_bus, &xs->xs_dc_dma);
2929 	xs->xs_idx = 0;
2930 }
2931 
2932 /*
2933  * Setup slot context, set Device Context Base Address, and issue
2934  * Set Address Device command.
2935  */
2936 static usbd_status
2937 xhci_set_address(struct usbd_device *dev, uint32_t slot, bool bsr)
2938 {
2939 	struct xhci_softc * const sc = XHCI_BUS2SC(dev->ud_bus);
2940 	struct xhci_slot *xs;
2941 	usbd_status err;
2942 
2943 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2944 	DPRINTFN(4, "slot %ju bsr %ju", slot, bsr, 0, 0);
2945 
2946 	xs = &sc->sc_slots[slot];
2947 
2948 	xhci_setup_ctx(dev->ud_pipe0);
2949 
2950 	HEXDUMP("input context", xhci_slot_get_icv(sc, xs, 0),
2951 	    sc->sc_ctxsz * 3);
2952 
2953 	xhci_set_dcba(sc, DMAADDR(&xs->xs_dc_dma, 0), slot);
2954 
2955 	err = xhci_address_device(sc, xhci_slot_get_icp(sc, xs, 0), slot, bsr);
2956 
2957 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
2958 	HEXDUMP("output context", xhci_slot_get_dcv(sc, xs, 0),
2959 	    sc->sc_ctxsz * 2);
2960 
2961 	return err;
2962 }
2963 
2964 /*
2965  * 4.8.2, 6.2.3.2
2966  * construct slot/endpoint context parameters and do syncmem
2967  */
2968 static void
2969 xhci_setup_ctx(struct usbd_pipe *pipe)
2970 {
2971 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
2972 	struct usbd_device *dev = pipe->up_dev;
2973 	struct xhci_slot * const xs = dev->ud_hcpriv;
2974 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
2975 	const u_int dci = xhci_ep_get_dci(ed);
2976 	const uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
2977 	uint32_t *cp;
2978 	uint16_t mps = UGETW(ed->wMaxPacketSize);
2979 	uint8_t speed = dev->ud_speed;
2980 	uint8_t ival = ed->bInterval;
2981 
2982 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
2983 	DPRINTFN(4, "pipe %#jx: slot %ju dci %ju speed %ju",
2984 	    (uintptr_t)pipe, xs->xs_idx, dci, speed);
2985 
2986 	/* set up initial input control context */
2987 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
2988 	cp[0] = htole32(0);
2989 	cp[1] = htole32(XHCI_INCTX_1_ADD_MASK(dci));
2990 	cp[1] |= htole32(XHCI_INCTX_1_ADD_MASK(XHCI_DCI_SLOT));
2991 	cp[7] = htole32(0);
2992 
2993 	/* set up input slot context */
2994 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_SLOT));
2995 	cp[0] =
2996 	    XHCI_SCTX_0_CTX_NUM_SET(dci) |
2997 	    XHCI_SCTX_0_SPEED_SET(xhci_speed2xspeed(speed));
2998 	cp[1] = 0;
2999 	cp[2] = XHCI_SCTX_2_IRQ_TARGET_SET(0);
3000 	cp[3] = 0;
3001 	xhci_setup_route(pipe, cp);
3002 	xhci_setup_tthub(pipe, cp);
3003 
3004 	cp[0] = htole32(cp[0]);
3005 	cp[1] = htole32(cp[1]);
3006 	cp[2] = htole32(cp[2]);
3007 	cp[3] = htole32(cp[3]);
3008 
3009 	/* set up input endpoint context */
3010 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(dci));
3011 	cp[0] =
3012 	    XHCI_EPCTX_0_EPSTATE_SET(0) |
3013 	    XHCI_EPCTX_0_MULT_SET(0) |
3014 	    XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
3015 	    XHCI_EPCTX_0_LSA_SET(0) |
3016 	    XHCI_EPCTX_0_MAX_ESIT_PAYLOAD_HI_SET(0);
3017 	cp[1] =
3018 	    XHCI_EPCTX_1_EPTYPE_SET(xhci_ep_get_type(ed)) |
3019 	    XHCI_EPCTX_1_HID_SET(0) |
3020 	    XHCI_EPCTX_1_MAXB_SET(0);
3021 
3022 	if (xfertype != UE_ISOCHRONOUS)
3023 		cp[1] |= XHCI_EPCTX_1_CERR_SET(3);
3024 
3025 	if (xfertype == UE_CONTROL)
3026 		cp[4] = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8); /* 6.2.3 */
3027 	else if (USB_IS_SS(speed))
3028 		cp[4] = XHCI_EPCTX_4_AVG_TRB_LEN_SET(mps);
3029 	else
3030 		cp[4] = XHCI_EPCTX_4_AVG_TRB_LEN_SET(UE_GET_SIZE(mps));
3031 
3032 	xhci_setup_maxburst(pipe, cp);
3033 
3034 	switch (xfertype) {
3035 	case UE_CONTROL:
3036 		break;
3037 	case UE_BULK:
3038 		/* XXX Set MaxPStreams, HID, and LSA if streams enabled */
3039 		break;
3040 	case UE_INTERRUPT:
3041 		if (pipe->up_interval != USBD_DEFAULT_INTERVAL)
3042 			ival = pipe->up_interval;
3043 
3044 		ival = xhci_bival2ival(ival, speed);
3045 		cp[0] |= XHCI_EPCTX_0_IVAL_SET(ival);
3046 		break;
3047 	case UE_ISOCHRONOUS:
3048 		if (pipe->up_interval != USBD_DEFAULT_INTERVAL)
3049 			ival = pipe->up_interval;
3050 
3051 		/* xHCI 6.2.3.6 Table 65, USB 2.0 9.6.6 */
3052 		if (speed == USB_SPEED_FULL)
3053 			ival += 3; /* 1ms -> 125us */
3054 		ival--;
3055 		cp[0] |= XHCI_EPCTX_0_IVAL_SET(ival);
3056 		break;
3057 	default:
3058 		break;
3059 	}
3060 	DPRINTFN(4, "setting ival %ju MaxBurst %#jx",
3061 	    XHCI_EPCTX_0_IVAL_GET(cp[0]), XHCI_EPCTX_1_MAXB_GET(cp[1]), 0, 0);
3062 
3063 	/* rewind TR dequeue pointer in xHC */
3064 	/* can't use xhci_ep_get_dci() yet? */
3065 	*(uint64_t *)(&cp[2]) = htole64(
3066 	    xhci_ring_trbp(&xs->xs_ep[dci].xe_tr, 0) |
3067 	    XHCI_EPCTX_2_DCS_SET(1));
3068 
3069 	cp[0] = htole32(cp[0]);
3070 	cp[1] = htole32(cp[1]);
3071 	cp[4] = htole32(cp[4]);
3072 
3073 	/* rewind TR dequeue pointer in driver */
3074 	struct xhci_ring *xr = &xs->xs_ep[dci].xe_tr;
3075 	mutex_enter(&xr->xr_lock);
3076 	xhci_host_dequeue(xr);
3077 	mutex_exit(&xr->xr_lock);
3078 
3079 	/* sync input contexts before they are read from memory */
3080 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
3081 }
3082 
3083 /*
3084  * Setup route string and roothub port of given device for slot context
3085  */
3086 static void
3087 xhci_setup_route(struct usbd_pipe *pipe, uint32_t *cp)
3088 {
3089 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
3090 	struct usbd_device *dev = pipe->up_dev;
3091 	struct usbd_port *up = dev->ud_powersrc;
3092 	struct usbd_device *hub;
3093 	struct usbd_device *adev;
3094 	uint8_t rhport = 0;
3095 	uint32_t route = 0;
3096 
3097 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3098 
3099 	/* Locate root hub port and Determine route string */
3100 	/* 4.3.3 route string does not include roothub port */
3101 	for (hub = dev; hub != NULL; hub = hub->ud_myhub) {
3102 		uint32_t dep;
3103 
3104 		DPRINTFN(4, "hub %#jx depth %jd upport %jp upportno %jd",
3105 		    (uintptr_t)hub, hub->ud_depth, (uintptr_t)hub->ud_powersrc,
3106 		    hub->ud_powersrc ? (uintptr_t)hub->ud_powersrc->up_portno :
3107 			 -1);
3108 
3109 		if (hub->ud_powersrc == NULL)
3110 			break;
3111 		dep = hub->ud_depth;
3112 		if (dep == 0)
3113 			break;
3114 		rhport = hub->ud_powersrc->up_portno;
3115 		if (dep > USB_HUB_MAX_DEPTH)
3116 			continue;
3117 
3118 		route |=
3119 		    (rhport > UHD_SS_NPORTS_MAX ? UHD_SS_NPORTS_MAX : rhport)
3120 		    << ((dep - 1) * 4);
3121 	}
3122 	route = route >> 4;
3123 	size_t bn = hub == sc->sc_bus.ub_roothub ? 0 : 1;
3124 
3125 	/* Locate port on upstream high speed hub */
3126 	for (adev = dev, hub = up->up_parent;
3127 	     hub != NULL && hub->ud_speed != USB_SPEED_HIGH;
3128 	     adev = hub, hub = hub->ud_myhub)
3129 		;
3130 	if (hub) {
3131 		int p;
3132 		for (p = 0; p < hub->ud_hub->uh_hubdesc.bNbrPorts; p++) {
3133 			if (hub->ud_hub->uh_ports[p].up_dev == adev) {
3134 				dev->ud_myhsport = &hub->ud_hub->uh_ports[p];
3135 				goto found;
3136 			}
3137 		}
3138 		panic("%s: cannot find HS port", __func__);
3139 	found:
3140 		DPRINTFN(4, "high speed port %jd", p, 0, 0, 0);
3141 	} else {
3142 		dev->ud_myhsport = NULL;
3143 	}
3144 
3145 	const size_t ctlrport = xhci_rhport2ctlrport(sc, bn, rhport);
3146 
3147 	DPRINTFN(4, "rhport %ju ctlrport %ju Route %05jx hub %#jx", rhport,
3148 	    ctlrport, route, (uintptr_t)hub);
3149 
3150 	cp[0] |= XHCI_SCTX_0_ROUTE_SET(route);
3151 	cp[1] |= XHCI_SCTX_1_RH_PORT_SET(ctlrport);
3152 }
3153 
3154 /*
3155  * Setup whether device is hub, whether device uses MTT, and
3156  * TT informations if it uses MTT.
3157  */
3158 static void
3159 xhci_setup_tthub(struct usbd_pipe *pipe, uint32_t *cp)
3160 {
3161 	struct usbd_device *dev = pipe->up_dev;
3162 	struct usbd_port *myhsport = dev->ud_myhsport;
3163 	usb_device_descriptor_t * const dd = &dev->ud_ddesc;
3164 	uint32_t speed = dev->ud_speed;
3165 	uint8_t rhaddr = dev->ud_bus->ub_rhaddr;
3166 	uint8_t tthubslot, ttportnum;
3167 	bool ishub;
3168 	bool usemtt;
3169 
3170 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3171 
3172 	/*
3173 	 * 6.2.2, Table 57-60, 6.2.2.1, 6.2.2.2
3174 	 * tthubslot:
3175 	 *   This is the slot ID of parent HS hub
3176 	 *   if LS/FS device is connected && connected through HS hub.
3177 	 *   This is 0 if device is not LS/FS device ||
3178 	 *   parent hub is not HS hub ||
3179 	 *   attached to root hub.
3180 	 * ttportnum:
3181 	 *   This is the downstream facing port of parent HS hub
3182 	 *   if LS/FS device is connected.
3183 	 *   This is 0 if device is not LS/FS device ||
3184 	 *   parent hub is not HS hub ||
3185 	 *   attached to root hub.
3186 	 */
3187 	if (myhsport &&
3188 	    myhsport->up_parent->ud_addr != rhaddr &&
3189 	    (speed == USB_SPEED_LOW || speed == USB_SPEED_FULL)) {
3190 		ttportnum = myhsport->up_portno;
3191 		tthubslot = myhsport->up_parent->ud_addr;
3192 	} else {
3193 		ttportnum = 0;
3194 		tthubslot = 0;
3195 	}
3196 	DPRINTFN(4, "myhsport %#jx ttportnum=%jd tthubslot=%jd",
3197 	    (uintptr_t)myhsport, ttportnum, tthubslot, 0);
3198 
3199 	/* ishub is valid after reading UDESC_DEVICE */
3200 	ishub = (dd->bDeviceClass == UDCLASS_HUB);
3201 
3202 	/* dev->ud_hub is valid after reading UDESC_HUB */
3203 	if (ishub && dev->ud_hub) {
3204 		usb_hub_descriptor_t *hd = &dev->ud_hub->uh_hubdesc;
3205 		uint8_t ttt =
3206 		    __SHIFTOUT(UGETW(hd->wHubCharacteristics), UHD_TT_THINK);
3207 
3208 		cp[1] |= XHCI_SCTX_1_NUM_PORTS_SET(hd->bNbrPorts);
3209 		cp[2] |= XHCI_SCTX_2_TT_THINK_TIME_SET(ttt);
3210 		DPRINTFN(4, "nports=%jd ttt=%jd", hd->bNbrPorts, ttt, 0, 0);
3211 	}
3212 
3213 #define IS_MTTHUB(dd) \
3214      ((dd)->bDeviceProtocol == UDPROTO_HSHUBMTT)
3215 
3216 	/*
3217 	 * MTT flag is set if
3218 	 * 1. this is HS hub && MTTs are supported and enabled;  or
3219 	 * 2. this is LS or FS device && there is a parent HS hub where MTTs
3220 	 *    are supported and enabled.
3221 	 *
3222 	 * XXX enabled is not tested yet
3223 	 */
3224 	if (ishub && speed == USB_SPEED_HIGH && IS_MTTHUB(dd))
3225 		usemtt = true;
3226 	else if ((speed == USB_SPEED_LOW || speed == USB_SPEED_FULL) &&
3227 	    myhsport &&
3228 	    myhsport->up_parent->ud_addr != rhaddr &&
3229 	    IS_MTTHUB(&myhsport->up_parent->ud_ddesc))
3230 		usemtt = true;
3231 	else
3232 		usemtt = false;
3233 	DPRINTFN(4, "class %ju proto %ju ishub %jd usemtt %jd",
3234 	    dd->bDeviceClass, dd->bDeviceProtocol, ishub, usemtt);
3235 
3236 #undef IS_MTTHUB
3237 
3238 	cp[0] |=
3239 	    XHCI_SCTX_0_HUB_SET(ishub ? 1 : 0) |
3240 	    XHCI_SCTX_0_MTT_SET(usemtt ? 1 : 0);
3241 	cp[2] |=
3242 	    XHCI_SCTX_2_TT_HUB_SID_SET(tthubslot) |
3243 	    XHCI_SCTX_2_TT_PORT_NUM_SET(ttportnum);
3244 }
3245 
3246 /* set up params for periodic endpoint */
3247 static void
3248 xhci_setup_maxburst(struct usbd_pipe *pipe, uint32_t *cp)
3249 {
3250 	struct usbd_device *dev = pipe->up_dev;
3251 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
3252 	const uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
3253 	usbd_desc_iter_t iter;
3254 	const usb_cdc_descriptor_t *cdcd;
3255 	uint32_t maxb = 0;
3256 	uint16_t mps = UGETW(ed->wMaxPacketSize);
3257 	uint8_t speed = dev->ud_speed;
3258 	uint8_t ep;
3259 
3260 	/* config desc is NULL when opening ep0 */
3261 	if (dev == NULL || dev->ud_cdesc == NULL)
3262 		goto no_cdcd;
3263 	cdcd = (const usb_cdc_descriptor_t *)usb_find_desc(dev,
3264 	    UDESC_INTERFACE, USBD_CDCSUBTYPE_ANY);
3265 	if (cdcd == NULL)
3266 		goto no_cdcd;
3267 	usb_desc_iter_init(dev, &iter);
3268 	iter.cur = (const void *)cdcd;
3269 
3270 	/* find endpoint_ss_comp desc for ep of this pipe */
3271 	for (ep = 0;;) {
3272 		cdcd = (const usb_cdc_descriptor_t *)usb_desc_iter_next(&iter);
3273 		if (cdcd == NULL)
3274 			break;
3275 		if (ep == 0 && cdcd->bDescriptorType == UDESC_ENDPOINT) {
3276 			ep = ((const usb_endpoint_descriptor_t *)cdcd)->
3277 			    bEndpointAddress;
3278 			if (UE_GET_ADDR(ep) ==
3279 			    UE_GET_ADDR(ed->bEndpointAddress)) {
3280 				cdcd = (const usb_cdc_descriptor_t *)
3281 				    usb_desc_iter_next(&iter);
3282 				break;
3283 			}
3284 			ep = 0;
3285 		}
3286 	}
3287 	if (cdcd != NULL && cdcd->bDescriptorType == UDESC_ENDPOINT_SS_COMP) {
3288 		const usb_endpoint_ss_comp_descriptor_t * esscd =
3289 		    (const usb_endpoint_ss_comp_descriptor_t *)cdcd;
3290 		maxb = esscd->bMaxBurst;
3291 	}
3292 
3293  no_cdcd:
3294 	/* 6.2.3.4,  4.8.2.4 */
3295 	if (USB_IS_SS(speed)) {
3296 		/* USB 3.1  9.6.6 */
3297 		cp[1] |= XHCI_EPCTX_1_MAXP_SIZE_SET(mps);
3298 		/* USB 3.1  9.6.7 */
3299 		cp[1] |= XHCI_EPCTX_1_MAXB_SET(maxb);
3300 #ifdef notyet
3301 		if (xfertype == UE_ISOCHRONOUS) {
3302 		}
3303 		if (XHCI_HCC2_LEC(sc->sc_hcc2) != 0) {
3304 			/* use ESIT */
3305 			cp[4] |= XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(x);
3306 			cp[0] |= XHCI_EPCTX_0_MAX_ESIT_PAYLOAD_HI_SET(x);
3307 
3308 			/* XXX if LEC = 1, set ESIT instead */
3309 			cp[0] |= XHCI_EPCTX_0_MULT_SET(0);
3310 		} else {
3311 			/* use ival */
3312 		}
3313 #endif
3314 	} else {
3315 		/* USB 2.0  9.6.6 */
3316 		cp[1] |= XHCI_EPCTX_1_MAXP_SIZE_SET(UE_GET_SIZE(mps));
3317 
3318 		/* 6.2.3.4 */
3319 		if (speed == USB_SPEED_HIGH &&
3320 		   (xfertype == UE_ISOCHRONOUS || xfertype == UE_INTERRUPT)) {
3321 			maxb = UE_GET_TRANS(mps);
3322 		} else {
3323 			/* LS/FS or HS CTRL or HS BULK */
3324 			maxb = 0;
3325 		}
3326 		cp[1] |= XHCI_EPCTX_1_MAXB_SET(maxb);
3327 	}
3328 }
3329 
3330 /*
3331  * Convert endpoint bInterval value to endpoint context interval value
3332  * for Interrupt pipe.
3333  * xHCI 6.2.3.6 Table 65, USB 2.0 9.6.6
3334  */
3335 static uint32_t
3336 xhci_bival2ival(uint32_t ival, uint32_t speed)
3337 {
3338 	if (speed == USB_SPEED_LOW || speed == USB_SPEED_FULL) {
3339 		int i;
3340 
3341 		/*
3342 		 * round ival down to "the nearest base 2 multiple of
3343 		 * bInterval * 8".
3344 		 * bInterval is at most 255 as its type is uByte.
3345 		 * 255(ms) = 2040(x 125us) < 2^11, so start with 10.
3346 		 */
3347 		for (i = 10; i > 0; i--) {
3348 			if ((ival * 8) >= (1 << i))
3349 				break;
3350 		}
3351 		ival = i;
3352 	} else {
3353 		/* Interval = bInterval-1 for SS/HS */
3354 		ival--;
3355 	}
3356 
3357 	return ival;
3358 }
3359 
3360 /* ----- */
3361 
3362 static void
3363 xhci_noop(struct usbd_pipe *pipe)
3364 {
3365 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3366 }
3367 
3368 /*
3369  * Process root hub request.
3370  */
3371 static int
3372 xhci_roothub_ctrl(struct usbd_bus *bus, usb_device_request_t *req,
3373     void *buf, int buflen)
3374 {
3375 	struct xhci_softc * const sc = XHCI_BUS2SC(bus);
3376 	usb_port_status_t ps;
3377 	int l, totlen = 0;
3378 	uint16_t len, value, index;
3379 	int port, i;
3380 	uint32_t v;
3381 
3382 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3383 
3384 	if (sc->sc_dying)
3385 		return -1;
3386 
3387 	size_t bn = bus == &sc->sc_bus ? 0 : 1;
3388 
3389 	len = UGETW(req->wLength);
3390 	value = UGETW(req->wValue);
3391 	index = UGETW(req->wIndex);
3392 
3393 	DPRINTFN(12, "rhreq: %04jx %04jx %04jx %04jx",
3394 	    req->bmRequestType | (req->bRequest << 8), value, index, len);
3395 
3396 #define C(x,y) ((x) | ((y) << 8))
3397 	switch (C(req->bRequest, req->bmRequestType)) {
3398 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3399 		DPRINTFN(8, "getdesc: wValue=0x%04jx", value, 0, 0, 0);
3400 		if (len == 0)
3401 			break;
3402 		switch (value) {
3403 #define sd ((usb_string_descriptor_t *)buf)
3404 		case C(2, UDESC_STRING):
3405 			/* Product */
3406 			totlen = usb_makestrdesc(sd, len, "xHCI root hub");
3407 			break;
3408 #undef sd
3409 		default:
3410 			/* default from usbroothub */
3411 			return buflen;
3412 		}
3413 		break;
3414 
3415 	/* Hub requests */
3416 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3417 		break;
3418 	/* Clear Port Feature request */
3419 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER): {
3420 		const size_t cp = xhci_rhport2ctlrport(sc, bn, index);
3421 
3422 		DPRINTFN(4, "UR_CLEAR_PORT_FEAT bp=%jd feat=%jd bus=%jd cp=%jd",
3423 		    index, value, bn, cp);
3424 		if (index < 1 || index > sc->sc_rhportcount[bn]) {
3425 			return -1;
3426 		}
3427 		port = XHCI_PORTSC(cp);
3428 		v = xhci_op_read_4(sc, port);
3429 		DPRINTFN(4, "portsc=0x%08jx", v, 0, 0, 0);
3430 		v &= ~XHCI_PS_CLEAR;
3431 		switch (value) {
3432 		case UHF_PORT_ENABLE:
3433 			xhci_op_write_4(sc, port, v & ~XHCI_PS_PED);
3434 			break;
3435 		case UHF_PORT_SUSPEND:
3436 			return -1;
3437 		case UHF_PORT_POWER:
3438 			break;
3439 		case UHF_PORT_TEST:
3440 		case UHF_PORT_INDICATOR:
3441 			return -1;
3442 		case UHF_C_PORT_CONNECTION:
3443 			xhci_op_write_4(sc, port, v | XHCI_PS_CSC);
3444 			break;
3445 		case UHF_C_PORT_ENABLE:
3446 		case UHF_C_PORT_SUSPEND:
3447 		case UHF_C_PORT_OVER_CURRENT:
3448 			return -1;
3449 		case UHF_C_BH_PORT_RESET:
3450 			xhci_op_write_4(sc, port, v | XHCI_PS_WRC);
3451 			break;
3452 		case UHF_C_PORT_RESET:
3453 			xhci_op_write_4(sc, port, v | XHCI_PS_PRC);
3454 			break;
3455 		case UHF_C_PORT_LINK_STATE:
3456 			xhci_op_write_4(sc, port, v | XHCI_PS_PLC);
3457 			break;
3458 		case UHF_C_PORT_CONFIG_ERROR:
3459 			xhci_op_write_4(sc, port, v | XHCI_PS_CEC);
3460 			break;
3461 		default:
3462 			return -1;
3463 		}
3464 		break;
3465 	}
3466 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3467 		if (len == 0)
3468 			break;
3469 		if ((value & 0xff) != 0) {
3470 			return -1;
3471 		}
3472 		usb_hub_descriptor_t hubd;
3473 
3474 		totlen = min(buflen, sizeof(hubd));
3475 		memcpy(&hubd, buf, totlen);
3476 		hubd.bNbrPorts = sc->sc_rhportcount[bn];
3477 		USETW(hubd.wHubCharacteristics, UHD_PWR_NO_SWITCH);
3478 		hubd.bPwrOn2PwrGood = 200;
3479 		for (i = 0, l = sc->sc_rhportcount[bn]; l > 0; i++, l -= 8) {
3480 			/* XXX can't find out? */
3481 			hubd.DeviceRemovable[i++] = 0;
3482 		}
3483 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
3484 		totlen = min(totlen, hubd.bDescLength);
3485 		memcpy(buf, &hubd, totlen);
3486 		break;
3487 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3488 		if (len != 4) {
3489 			return -1;
3490 		}
3491 		memset(buf, 0, len); /* ? XXX */
3492 		totlen = len;
3493 		break;
3494 	/* Get Port Status request */
3495 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER): {
3496 		const size_t cp = xhci_rhport2ctlrport(sc, bn, index);
3497 
3498 		DPRINTFN(8, "get port status bn=%jd i=%jd cp=%ju",
3499 		    bn, index, cp, 0);
3500 		if (index < 1 || index > sc->sc_rhportcount[bn]) {
3501 			return -1;
3502 		}
3503 		if (len != 4) {
3504 			return -1;
3505 		}
3506 		v = xhci_op_read_4(sc, XHCI_PORTSC(cp));
3507 		DPRINTFN(4, "getrhportsc %jd %08jx", cp, v, 0, 0);
3508 		i = xhci_xspeed2psspeed(XHCI_PS_SPEED_GET(v));
3509 		if (v & XHCI_PS_CCS)	i |= UPS_CURRENT_CONNECT_STATUS;
3510 		if (v & XHCI_PS_PED)	i |= UPS_PORT_ENABLED;
3511 		if (v & XHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
3512 		//if (v & XHCI_PS_SUSP)	i |= UPS_SUSPEND;
3513 		if (v & XHCI_PS_PR)	i |= UPS_RESET;
3514 		if (v & XHCI_PS_PP) {
3515 			if (i & UPS_OTHER_SPEED)
3516 					i |= UPS_PORT_POWER_SS;
3517 			else
3518 					i |= UPS_PORT_POWER;
3519 		}
3520 		if (i & UPS_OTHER_SPEED)
3521 			i |= UPS_PORT_LS_SET(XHCI_PS_PLS_GET(v));
3522 		if (sc->sc_vendor_port_status)
3523 			i = sc->sc_vendor_port_status(sc, v, i);
3524 		USETW(ps.wPortStatus, i);
3525 		i = 0;
3526 		if (v & XHCI_PS_CSC)    i |= UPS_C_CONNECT_STATUS;
3527 		if (v & XHCI_PS_PEC)    i |= UPS_C_PORT_ENABLED;
3528 		if (v & XHCI_PS_OCC)    i |= UPS_C_OVERCURRENT_INDICATOR;
3529 		if (v & XHCI_PS_PRC)	i |= UPS_C_PORT_RESET;
3530 		if (v & XHCI_PS_WRC)	i |= UPS_C_BH_PORT_RESET;
3531 		if (v & XHCI_PS_PLC)	i |= UPS_C_PORT_LINK_STATE;
3532 		if (v & XHCI_PS_CEC)	i |= UPS_C_PORT_CONFIG_ERROR;
3533 		USETW(ps.wPortChange, i);
3534 		totlen = min(len, sizeof(ps));
3535 		memcpy(buf, &ps, totlen);
3536 		break;
3537 	}
3538 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3539 		return -1;
3540 	case C(UR_SET_HUB_DEPTH, UT_WRITE_CLASS_DEVICE):
3541 		break;
3542 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3543 		break;
3544 	/* Set Port Feature request */
3545 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER): {
3546 		int optval = (index >> 8) & 0xff;
3547 		index &= 0xff;
3548 		if (index < 1 || index > sc->sc_rhportcount[bn]) {
3549 			return -1;
3550 		}
3551 
3552 		const size_t cp = xhci_rhport2ctlrport(sc, bn, index);
3553 
3554 		port = XHCI_PORTSC(cp);
3555 		v = xhci_op_read_4(sc, port);
3556 		DPRINTFN(4, "index %jd cp %jd portsc=0x%08jx", index, cp, v, 0);
3557 		v &= ~XHCI_PS_CLEAR;
3558 		switch (value) {
3559 		case UHF_PORT_ENABLE:
3560 			xhci_op_write_4(sc, port, v | XHCI_PS_PED);
3561 			break;
3562 		case UHF_PORT_SUSPEND:
3563 			/* XXX suspend */
3564 			break;
3565 		case UHF_PORT_RESET:
3566 			v &= ~(XHCI_PS_PED | XHCI_PS_PR);
3567 			xhci_op_write_4(sc, port, v | XHCI_PS_PR);
3568 			/* Wait for reset to complete. */
3569 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
3570 			if (sc->sc_dying) {
3571 				return -1;
3572 			}
3573 			v = xhci_op_read_4(sc, port);
3574 			if (v & XHCI_PS_PR) {
3575 				xhci_op_write_4(sc, port, v & ~XHCI_PS_PR);
3576 				usb_delay_ms(&sc->sc_bus, 10);
3577 				/* XXX */
3578 			}
3579 			break;
3580 		case UHF_PORT_POWER:
3581 			/* XXX power control */
3582 			break;
3583 		/* XXX more */
3584 		case UHF_C_PORT_RESET:
3585 			xhci_op_write_4(sc, port, v | XHCI_PS_PRC);
3586 			break;
3587 		case UHF_PORT_U1_TIMEOUT:
3588 			if (XHCI_PS_SPEED_GET(v) < XHCI_PS_SPEED_SS) {
3589 				return -1;
3590 			}
3591 			port = XHCI_PORTPMSC(cp);
3592 			v = xhci_op_read_4(sc, port);
3593 			DPRINTFN(4, "index %jd cp %jd portpmsc=0x%08jx",
3594 			    index, cp, v, 0);
3595 			v &= ~XHCI_PM3_U1TO_SET(0xff);
3596 			v |= XHCI_PM3_U1TO_SET(optval);
3597 			xhci_op_write_4(sc, port, v);
3598 			break;
3599 		case UHF_PORT_U2_TIMEOUT:
3600 			if (XHCI_PS_SPEED_GET(v) < XHCI_PS_SPEED_SS) {
3601 				return -1;
3602 			}
3603 			port = XHCI_PORTPMSC(cp);
3604 			v = xhci_op_read_4(sc, port);
3605 			DPRINTFN(4, "index %jd cp %jd portpmsc=0x%08jx",
3606 			    index, cp, v, 0);
3607 			v &= ~XHCI_PM3_U2TO_SET(0xff);
3608 			v |= XHCI_PM3_U2TO_SET(optval);
3609 			xhci_op_write_4(sc, port, v);
3610 			break;
3611 		default:
3612 			return -1;
3613 		}
3614 	}
3615 		break;
3616 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
3617 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
3618 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
3619 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
3620 		break;
3621 	default:
3622 		/* default from usbroothub */
3623 		return buflen;
3624 	}
3625 
3626 	return totlen;
3627 }
3628 
3629 /* root hub interrupt */
3630 
3631 static usbd_status
3632 xhci_root_intr_transfer(struct usbd_xfer *xfer)
3633 {
3634 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3635 	usbd_status err;
3636 
3637 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3638 
3639 	/* Insert last in queue. */
3640 	mutex_enter(&sc->sc_lock);
3641 	err = usb_insert_transfer(xfer);
3642 	mutex_exit(&sc->sc_lock);
3643 	if (err)
3644 		return err;
3645 
3646 	/* Pipe isn't running, start first */
3647 	return xhci_root_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3648 }
3649 
3650 /* Wait for roothub port status/change */
3651 static usbd_status
3652 xhci_root_intr_start(struct usbd_xfer *xfer)
3653 {
3654 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3655 	const size_t bn = XHCI_XFER2BUS(xfer) == &sc->sc_bus ? 0 : 1;
3656 
3657 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3658 
3659 	if (sc->sc_dying)
3660 		return USBD_IOERROR;
3661 
3662 	mutex_enter(&sc->sc_lock);
3663 	sc->sc_intrxfer[bn] = xfer;
3664 	mutex_exit(&sc->sc_lock);
3665 
3666 	return USBD_IN_PROGRESS;
3667 }
3668 
3669 static void
3670 xhci_root_intr_abort(struct usbd_xfer *xfer)
3671 {
3672 	struct xhci_softc * const sc __diagused = XHCI_XFER2SC(xfer);
3673 
3674 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3675 
3676 	KASSERT(mutex_owned(&sc->sc_lock));
3677 	KASSERT(xfer->ux_pipe->up_intrxfer == xfer);
3678 
3679 	xfer->ux_status = USBD_CANCELLED;
3680 	usb_transfer_complete(xfer);
3681 }
3682 
3683 static void
3684 xhci_root_intr_close(struct usbd_pipe *pipe)
3685 {
3686 	struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
3687 	const struct usbd_xfer *xfer = pipe->up_intrxfer;
3688 	const size_t bn = XHCI_XFER2BUS(xfer) == &sc->sc_bus ? 0 : 1;
3689 
3690 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3691 
3692 	KASSERT(mutex_owned(&sc->sc_lock));
3693 
3694 	sc->sc_intrxfer[bn] = NULL;
3695 }
3696 
3697 static void
3698 xhci_root_intr_done(struct usbd_xfer *xfer)
3699 {
3700 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3701 
3702 }
3703 
3704 /* -------------- */
3705 /* device control */
3706 
3707 static usbd_status
3708 xhci_device_ctrl_transfer(struct usbd_xfer *xfer)
3709 {
3710 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3711 	usbd_status err;
3712 
3713 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3714 
3715 	/* Insert last in queue. */
3716 	mutex_enter(&sc->sc_lock);
3717 	err = usb_insert_transfer(xfer);
3718 	mutex_exit(&sc->sc_lock);
3719 	if (err)
3720 		return err;
3721 
3722 	/* Pipe isn't running, start first */
3723 	return xhci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3724 }
3725 
3726 static usbd_status
3727 xhci_device_ctrl_start(struct usbd_xfer *xfer)
3728 {
3729 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3730 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
3731 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
3732 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
3733 	struct xhci_xfer * const xx = XHCI_XFER2XXFER(xfer);
3734 	usb_device_request_t * const req = &xfer->ux_request;
3735 	const int isread = usbd_xfer_isread(xfer);
3736 	const uint32_t len = UGETW(req->wLength);
3737 	usb_dma_t * const dma = &xfer->ux_dmabuf;
3738 	uint64_t parameter;
3739 	uint32_t status;
3740 	uint32_t control;
3741 	u_int i;
3742 
3743 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3744 	DPRINTFN(12, "req: %04jx %04jx %04jx %04jx",
3745 	    req->bmRequestType | (req->bRequest << 8), UGETW(req->wValue),
3746 	    UGETW(req->wIndex), UGETW(req->wLength));
3747 
3748 	/* we rely on the bottom bits for extra info */
3749 	KASSERTMSG(((uintptr_t)xfer & 0x3) == 0x0, "xfer %zx",
3750 	    (uintptr_t) xfer);
3751 
3752 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) != 0);
3753 
3754 	i = 0;
3755 
3756 	/* setup phase */
3757 	memcpy(&parameter, req, sizeof(parameter));
3758 	status = XHCI_TRB_2_IRQ_SET(0) | XHCI_TRB_2_BYTES_SET(sizeof(*req));
3759 	control = ((len == 0) ? XHCI_TRB_3_TRT_NONE :
3760 	     (isread ? XHCI_TRB_3_TRT_IN : XHCI_TRB_3_TRT_OUT)) |
3761 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
3762 	    XHCI_TRB_3_IDT_BIT;
3763 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
3764 
3765 	if (len != 0) {
3766 		/* data phase */
3767 		parameter = DMAADDR(dma, 0);
3768 		KASSERTMSG(len <= 0x10000, "len %d", len);
3769 		status = XHCI_TRB_2_IRQ_SET(0) |
3770 		    XHCI_TRB_2_TDSZ_SET(1) |
3771 		    XHCI_TRB_2_BYTES_SET(len);
3772 		control = (isread ? XHCI_TRB_3_DIR_IN : 0) |
3773 		    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE) |
3774 		    (usbd_xfer_isread(xfer) ? XHCI_TRB_3_ISP_BIT : 0) |
3775 		    XHCI_TRB_3_IOC_BIT;
3776 		xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
3777 	}
3778 
3779 	parameter = 0;
3780 	status = XHCI_TRB_2_IRQ_SET(0);
3781 	/* the status stage has inverted direction */
3782 	control = ((isread && (len > 0)) ? 0 : XHCI_TRB_3_DIR_IN) |
3783 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE) |
3784 	    XHCI_TRB_3_IOC_BIT;
3785 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
3786 
3787 	mutex_enter(&tr->xr_lock);
3788 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
3789 	mutex_exit(&tr->xr_lock);
3790 
3791 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
3792 
3793 	if (xfer->ux_timeout && !xhci_polling_p(sc)) {
3794 		callout_reset(&xfer->ux_callout, mstohz(xfer->ux_timeout),
3795 		    xhci_timeout, xfer);
3796 	}
3797 
3798 	return USBD_IN_PROGRESS;
3799 }
3800 
3801 static void
3802 xhci_device_ctrl_done(struct usbd_xfer *xfer)
3803 {
3804 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3805 	usb_device_request_t *req = &xfer->ux_request;
3806 	int len = UGETW(req->wLength);
3807 	int rd = req->bmRequestType & UT_READ;
3808 
3809 	if (len)
3810 		usb_syncmem(&xfer->ux_dmabuf, 0, len,
3811 		    rd ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3812 }
3813 
3814 static void
3815 xhci_device_ctrl_abort(struct usbd_xfer *xfer)
3816 {
3817 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3818 
3819 	xhci_abort_xfer(xfer, USBD_CANCELLED);
3820 }
3821 
3822 static void
3823 xhci_device_ctrl_close(struct usbd_pipe *pipe)
3824 {
3825 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3826 
3827 	xhci_close_pipe(pipe);
3828 }
3829 
3830 /* ------------------ */
3831 /* device isochronous */
3832 
3833 /* ----------- */
3834 /* device bulk */
3835 
3836 static usbd_status
3837 xhci_device_bulk_transfer(struct usbd_xfer *xfer)
3838 {
3839 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3840 	usbd_status err;
3841 
3842 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3843 
3844 	/* Insert last in queue. */
3845 	mutex_enter(&sc->sc_lock);
3846 	err = usb_insert_transfer(xfer);
3847 	mutex_exit(&sc->sc_lock);
3848 	if (err)
3849 		return err;
3850 
3851 	/*
3852 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
3853 	 * so start it first.
3854 	 */
3855 	return xhci_device_bulk_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3856 }
3857 
3858 static usbd_status
3859 xhci_device_bulk_start(struct usbd_xfer *xfer)
3860 {
3861 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3862 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
3863 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
3864 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
3865 	struct xhci_xfer * const xx = XHCI_XFER2XXFER(xfer);
3866 	const uint32_t len = xfer->ux_length;
3867 	usb_dma_t * const dma = &xfer->ux_dmabuf;
3868 	uint64_t parameter;
3869 	uint32_t status;
3870 	uint32_t control;
3871 	u_int i = 0;
3872 
3873 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3874 
3875 	DPRINTFN(15, "%#jx slot %ju dci %ju", (uintptr_t)xfer, xs->xs_idx, dci,
3876 	    0);
3877 
3878 	if (sc->sc_dying)
3879 		return USBD_IOERROR;
3880 
3881 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) == 0);
3882 
3883 	parameter = DMAADDR(dma, 0);
3884 	/*
3885 	 * XXX: (dsl) The physical buffer must not cross a 64k boundary.
3886 	 * If the user supplied buffer crosses such a boundary then 2
3887 	 * (or more) TRB should be used.
3888 	 * If multiple TRB are used the td_size field must be set correctly.
3889 	 * For v1.0 devices (like ivy bridge) this is the number of usb data
3890 	 * blocks needed to complete the transfer.
3891 	 * Setting it to 1 in the last TRB causes an extra zero-length
3892 	 * data block be sent.
3893 	 * The earlier documentation differs, I don't know how it behaves.
3894 	 */
3895 	KASSERTMSG(len <= 0x10000, "len %d", len);
3896 	status = XHCI_TRB_2_IRQ_SET(0) |
3897 	    XHCI_TRB_2_TDSZ_SET(1) |
3898 	    XHCI_TRB_2_BYTES_SET(len);
3899 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL) |
3900 	    (usbd_xfer_isread(xfer) ? XHCI_TRB_3_ISP_BIT : 0) |
3901 	    XHCI_TRB_3_IOC_BIT;
3902 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
3903 
3904 	mutex_enter(&tr->xr_lock);
3905 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
3906 	mutex_exit(&tr->xr_lock);
3907 
3908 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
3909 
3910 	if (xfer->ux_timeout && !xhci_polling_p(sc)) {
3911 		callout_reset(&xfer->ux_callout, mstohz(xfer->ux_timeout),
3912 		    xhci_timeout, xfer);
3913 	}
3914 
3915 	return USBD_IN_PROGRESS;
3916 }
3917 
3918 static void
3919 xhci_device_bulk_done(struct usbd_xfer *xfer)
3920 {
3921 #ifdef USB_DEBUG
3922 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
3923 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
3924 #endif
3925 	const int isread = usbd_xfer_isread(xfer);
3926 
3927 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3928 
3929 	DPRINTFN(15, "%#jx slot %ju dci %ju", (uintptr_t)xfer, xs->xs_idx, dci,
3930 	    0);
3931 
3932 	usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
3933 	    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
3934 }
3935 
3936 static void
3937 xhci_device_bulk_abort(struct usbd_xfer *xfer)
3938 {
3939 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3940 
3941 	xhci_abort_xfer(xfer, USBD_CANCELLED);
3942 }
3943 
3944 static void
3945 xhci_device_bulk_close(struct usbd_pipe *pipe)
3946 {
3947 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3948 
3949 	xhci_close_pipe(pipe);
3950 }
3951 
3952 /* ---------------- */
3953 /* device interrupt */
3954 
3955 static usbd_status
3956 xhci_device_intr_transfer(struct usbd_xfer *xfer)
3957 {
3958 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3959 	usbd_status err;
3960 
3961 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3962 
3963 	/* Insert last in queue. */
3964 	mutex_enter(&sc->sc_lock);
3965 	err = usb_insert_transfer(xfer);
3966 	mutex_exit(&sc->sc_lock);
3967 	if (err)
3968 		return err;
3969 
3970 	/*
3971 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
3972 	 * so start it first.
3973 	 */
3974 	return xhci_device_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
3975 }
3976 
3977 static usbd_status
3978 xhci_device_intr_start(struct usbd_xfer *xfer)
3979 {
3980 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
3981 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
3982 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
3983 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
3984 	struct xhci_xfer * const xx = XHCI_XFER2XXFER(xfer);
3985 	const uint32_t len = xfer->ux_length;
3986 	const bool polling = xhci_polling_p(sc);
3987 	usb_dma_t * const dma = &xfer->ux_dmabuf;
3988 	uint64_t parameter;
3989 	uint32_t status;
3990 	uint32_t control;
3991 	u_int i = 0;
3992 
3993 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
3994 
3995 	DPRINTFN(15, "%#jx slot %ju dci %ju", (uintptr_t)xfer, xs->xs_idx, dci,
3996 	    0);
3997 
3998 	if (sc->sc_dying)
3999 		return USBD_IOERROR;
4000 
4001 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) == 0);
4002 
4003 	parameter = DMAADDR(dma, 0);
4004 	KASSERTMSG(len <= 0x10000, "len %d", len);
4005 	status = XHCI_TRB_2_IRQ_SET(0) |
4006 	    XHCI_TRB_2_TDSZ_SET(1) |
4007 	    XHCI_TRB_2_BYTES_SET(len);
4008 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL) |
4009 	    (usbd_xfer_isread(xfer) ? XHCI_TRB_3_ISP_BIT : 0) |
4010 	    XHCI_TRB_3_IOC_BIT;
4011 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
4012 
4013 	if (!polling)
4014 		mutex_enter(&tr->xr_lock);
4015 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
4016 	if (!polling)
4017 		mutex_exit(&tr->xr_lock);
4018 
4019 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
4020 
4021 	if (xfer->ux_timeout && !polling) {
4022 		callout_reset(&xfer->ux_callout, mstohz(xfer->ux_timeout),
4023 		    xhci_timeout, xfer);
4024 	}
4025 
4026 	return USBD_IN_PROGRESS;
4027 }
4028 
4029 static void
4030 xhci_device_intr_done(struct usbd_xfer *xfer)
4031 {
4032 	struct xhci_softc * const sc __diagused = XHCI_XFER2SC(xfer);
4033 #ifdef USB_DEBUG
4034 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
4035 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
4036 #endif
4037 	const int isread = usbd_xfer_isread(xfer);
4038 
4039 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
4040 
4041 	DPRINTFN(15, "%#jx slot %ju dci %ju", (uintptr_t)xfer, xs->xs_idx, dci,
4042 	    0);
4043 
4044 	KASSERT(xhci_polling_p(sc) || mutex_owned(&sc->sc_lock));
4045 
4046 	usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
4047 	    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
4048 }
4049 
4050 static void
4051 xhci_device_intr_abort(struct usbd_xfer *xfer)
4052 {
4053 	struct xhci_softc * const sc __diagused = XHCI_XFER2SC(xfer);
4054 
4055 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
4056 
4057 	KASSERT(mutex_owned(&sc->sc_lock));
4058 	DPRINTFN(15, "%#jx", (uintptr_t)xfer, 0, 0, 0);
4059 	KASSERT(xfer->ux_pipe->up_intrxfer == xfer);
4060 	xhci_abort_xfer(xfer, USBD_CANCELLED);
4061 }
4062 
4063 static void
4064 xhci_device_intr_close(struct usbd_pipe *pipe)
4065 {
4066 	//struct xhci_softc * const sc = XHCI_PIPE2SC(pipe);
4067 
4068 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
4069 	DPRINTFN(15, "%#jx", (uintptr_t)pipe, 0, 0, 0);
4070 
4071 	xhci_close_pipe(pipe);
4072 }
4073 
4074 /* ------------ */
4075 
4076 static void
4077 xhci_timeout(void *addr)
4078 {
4079 	struct xhci_xfer * const xx = addr;
4080 	struct usbd_xfer * const xfer = &xx->xx_xfer;
4081 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
4082 
4083 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
4084 
4085 	if (sc->sc_dying) {
4086 		return;
4087 	}
4088 
4089 	usb_init_task(&xx->xx_abort_task, xhci_timeout_task, addr,
4090 	    USB_TASKQ_MPSAFE);
4091 	usb_add_task(xx->xx_xfer.ux_pipe->up_dev, &xx->xx_abort_task,
4092 	    USB_TASKQ_HC);
4093 }
4094 
4095 static void
4096 xhci_timeout_task(void *addr)
4097 {
4098 	struct usbd_xfer * const xfer = addr;
4099 	struct xhci_softc * const sc = XHCI_XFER2SC(xfer);
4100 
4101 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
4102 
4103 	mutex_enter(&sc->sc_lock);
4104 	xhci_abort_xfer(xfer, USBD_TIMEOUT);
4105 	mutex_exit(&sc->sc_lock);
4106 }
4107