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