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