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