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