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