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