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