Home | History | Annotate | Line # | Download | only in usb
xhci.c revision 1.28.2.33
      1 /*	$NetBSD: xhci.c,v 1.28.2.33 2015/06/26 15:51:05 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 3.1 specification
     31  *  http://www.usb.org/developers/docs/usb_31_040315.zip
     32  * USB rev 2.0 specification
     33  *  http://www.usb.org/developers/docs/usb20_docs/usb_20_031815.zip
     34  * xHCI rev 1.1 specification
     35  *  http://www.intel.com/content/dam/www/public/us/en/documents/technical-specifications/extensible-host-controler-interface-usb-xhci.pdf
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 __KERNEL_RCSID(0, "$NetBSD: xhci.c,v 1.28.2.33 2015/06/26 15:51:05 skrll Exp $");
     40 
     41 #include "opt_usb.h"
     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 *);
    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 usbd_status xhci_set_dequeue(struct usbd_pipe *);
    146 
    147 static usbd_status xhci_do_command(struct xhci_softc * const,
    148     struct xhci_trb * const, int);
    149 static usbd_status xhci_do_command1(struct xhci_softc * const,
    150     struct xhci_trb * const, int, int);
    151 static usbd_status xhci_do_command_locked(struct xhci_softc * const,
    152     struct xhci_trb * const, int);
    153 static usbd_status xhci_init_slot(struct usbd_device *, uint32_t, int, int);
    154 static usbd_status xhci_enable_slot(struct xhci_softc * const,
    155     uint8_t * const);
    156 static usbd_status xhci_disable_slot(struct xhci_softc * const, uint8_t);
    157 static usbd_status xhci_address_device(struct xhci_softc * const,
    158     uint64_t, uint8_t, bool);
    159 static usbd_status xhci_update_ep0_mps(struct xhci_softc * const,
    160     struct xhci_slot * const, u_int);
    161 static usbd_status xhci_ring_init(struct xhci_softc * const,
    162     struct xhci_ring * const, size_t, size_t);
    163 static void xhci_ring_free(struct xhci_softc * const, struct xhci_ring * const);
    164 
    165 static void xhci_noop(struct usbd_pipe *);
    166 
    167 static usbd_status xhci_root_intr_transfer(struct usbd_xfer *);
    168 static usbd_status xhci_root_intr_start(struct usbd_xfer *);
    169 static void xhci_root_intr_abort(struct usbd_xfer *);
    170 static void xhci_root_intr_close(struct usbd_pipe *);
    171 static void xhci_root_intr_done(struct usbd_xfer *);
    172 
    173 static usbd_status xhci_device_ctrl_transfer(struct usbd_xfer *);
    174 static usbd_status xhci_device_ctrl_start(struct usbd_xfer *);
    175 static void xhci_device_ctrl_abort(struct usbd_xfer *);
    176 static void xhci_device_ctrl_close(struct usbd_pipe *);
    177 static void xhci_device_ctrl_done(struct usbd_xfer *);
    178 
    179 static usbd_status xhci_device_intr_transfer(struct usbd_xfer *);
    180 static usbd_status xhci_device_intr_start(struct usbd_xfer *);
    181 static void xhci_device_intr_abort(struct usbd_xfer *);
    182 static void xhci_device_intr_close(struct usbd_pipe *);
    183 static void xhci_device_intr_done(struct usbd_xfer *);
    184 
    185 static usbd_status xhci_device_bulk_transfer(struct usbd_xfer *);
    186 static usbd_status xhci_device_bulk_start(struct usbd_xfer *);
    187 static void xhci_device_bulk_abort(struct usbd_xfer *);
    188 static void xhci_device_bulk_close(struct usbd_pipe *);
    189 static void xhci_device_bulk_done(struct usbd_xfer *);
    190 
    191 static void xhci_timeout(void *);
    192 static void xhci_timeout_task(void *);
    193 
    194 static const struct usbd_bus_methods xhci_bus_methods = {
    195 	.ubm_open = xhci_open,
    196 	.ubm_softint = xhci_softintr,
    197 	.ubm_dopoll = xhci_poll,
    198 	.ubm_allocx = xhci_allocx,
    199 	.ubm_freex = xhci_freex,
    200 	.ubm_getlock = xhci_get_lock,
    201 	.ubm_newdev = xhci_new_device,
    202 	.ubm_rhctrl = xhci_roothub_ctrl,
    203 };
    204 
    205 static const struct usbd_pipe_methods xhci_root_intr_methods = {
    206 	.upm_transfer = xhci_root_intr_transfer,
    207 	.upm_start = xhci_root_intr_start,
    208 	.upm_abort = xhci_root_intr_abort,
    209 	.upm_close = xhci_root_intr_close,
    210 	.upm_cleartoggle = xhci_noop,
    211 	.upm_done = xhci_root_intr_done,
    212 };
    213 
    214 
    215 static const struct usbd_pipe_methods xhci_device_ctrl_methods = {
    216 	.upm_transfer = xhci_device_ctrl_transfer,
    217 	.upm_start = xhci_device_ctrl_start,
    218 	.upm_abort = xhci_device_ctrl_abort,
    219 	.upm_close = xhci_device_ctrl_close,
    220 	.upm_cleartoggle = xhci_noop,
    221 	.upm_done = xhci_device_ctrl_done,
    222 };
    223 
    224 static const struct usbd_pipe_methods xhci_device_isoc_methods = {
    225 	.upm_cleartoggle = xhci_noop,
    226 };
    227 
    228 static const struct usbd_pipe_methods xhci_device_bulk_methods = {
    229 	.upm_transfer = xhci_device_bulk_transfer,
    230 	.upm_start = xhci_device_bulk_start,
    231 	.upm_abort = xhci_device_bulk_abort,
    232 	.upm_close = xhci_device_bulk_close,
    233 	.upm_cleartoggle = xhci_noop,
    234 	.upm_done = xhci_device_bulk_done,
    235 };
    236 
    237 static const struct usbd_pipe_methods xhci_device_intr_methods = {
    238 	.upm_transfer = xhci_device_intr_transfer,
    239 	.upm_start = xhci_device_intr_start,
    240 	.upm_abort = xhci_device_intr_abort,
    241 	.upm_close = xhci_device_intr_close,
    242 	.upm_cleartoggle = xhci_noop,
    243 	.upm_done = xhci_device_intr_done,
    244 };
    245 
    246 static inline uint32_t
    247 xhci_read_1(const struct xhci_softc * const sc, bus_size_t offset)
    248 {
    249 	return bus_space_read_1(sc->sc_iot, sc->sc_ioh, offset);
    250 }
    251 
    252 static inline uint32_t
    253 xhci_read_4(const struct xhci_softc * const sc, bus_size_t offset)
    254 {
    255 	return bus_space_read_4(sc->sc_iot, sc->sc_ioh, offset);
    256 }
    257 
    258 static inline void
    259 xhci_write_1(const struct xhci_softc * const sc, bus_size_t offset,
    260     uint32_t value)
    261 {
    262 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, offset, value);
    263 }
    264 
    265 #if 0 /* unused */
    266 static inline void
    267 xhci_write_4(const struct xhci_softc * const sc, bus_size_t offset,
    268     uint32_t value)
    269 {
    270 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, offset, value);
    271 }
    272 #endif /* unused */
    273 
    274 static inline uint32_t
    275 xhci_cap_read_4(const struct xhci_softc * const sc, bus_size_t offset)
    276 {
    277 	return bus_space_read_4(sc->sc_iot, sc->sc_cbh, offset);
    278 }
    279 
    280 static inline uint32_t
    281 xhci_op_read_4(const struct xhci_softc * const sc, bus_size_t offset)
    282 {
    283 	return bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
    284 }
    285 
    286 static inline void
    287 xhci_op_write_4(const struct xhci_softc * const sc, bus_size_t offset,
    288     uint32_t value)
    289 {
    290 	bus_space_write_4(sc->sc_iot, sc->sc_obh, offset, value);
    291 }
    292 
    293 #if 0 /* unused */
    294 static inline uint64_t
    295 xhci_op_read_8(const struct xhci_softc * const sc, bus_size_t offset)
    296 {
    297 	uint64_t value;
    298 
    299 	if (sc->sc_ac64) {
    300 #ifdef XHCI_USE_BUS_SPACE_8
    301 		value = bus_space_read_8(sc->sc_iot, sc->sc_obh, offset);
    302 #else
    303 		value = bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
    304 		value |= (uint64_t)bus_space_read_4(sc->sc_iot, sc->sc_obh,
    305 		    offset + 4) << 32;
    306 #endif
    307 	} else {
    308 		value = bus_space_read_4(sc->sc_iot, sc->sc_obh, offset);
    309 	}
    310 
    311 	return value;
    312 }
    313 #endif /* unused */
    314 
    315 static inline void
    316 xhci_op_write_8(const struct xhci_softc * const sc, bus_size_t offset,
    317     uint64_t value)
    318 {
    319 	if (sc->sc_ac64) {
    320 #ifdef XHCI_USE_BUS_SPACE_8
    321 		bus_space_write_8(sc->sc_iot, sc->sc_obh, offset, value);
    322 #else
    323 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset + 0,
    324 		    (value >> 0) & 0xffffffff);
    325 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset + 4,
    326 		    (value >> 32) & 0xffffffff);
    327 #endif
    328 	} else {
    329 		bus_space_write_4(sc->sc_iot, sc->sc_obh, offset, value);
    330 	}
    331 }
    332 
    333 static inline uint32_t
    334 xhci_rt_read_4(const struct xhci_softc * const sc, bus_size_t offset)
    335 {
    336 	return bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
    337 }
    338 
    339 static inline void
    340 xhci_rt_write_4(const struct xhci_softc * const sc, bus_size_t offset,
    341     uint32_t value)
    342 {
    343 	bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset, value);
    344 }
    345 
    346 #if 0 /* unused */
    347 static inline uint64_t
    348 xhci_rt_read_8(const struct xhci_softc * const sc, bus_size_t offset)
    349 {
    350 	uint64_t value;
    351 
    352 	if (sc->sc_ac64) {
    353 #ifdef XHCI_USE_BUS_SPACE_8
    354 		value = bus_space_read_8(sc->sc_iot, sc->sc_rbh, offset);
    355 #else
    356 		value = bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
    357 		value |= (uint64_t)bus_space_read_4(sc->sc_iot, sc->sc_rbh,
    358 		    offset + 4) << 32;
    359 #endif
    360 	} else {
    361 		value = bus_space_read_4(sc->sc_iot, sc->sc_rbh, offset);
    362 	}
    363 
    364 	return value;
    365 }
    366 #endif /* unused */
    367 
    368 static inline void
    369 xhci_rt_write_8(const struct xhci_softc * const sc, bus_size_t offset,
    370     uint64_t value)
    371 {
    372 	if (sc->sc_ac64) {
    373 #ifdef XHCI_USE_BUS_SPACE_8
    374 		bus_space_write_8(sc->sc_iot, sc->sc_rbh, offset, value);
    375 #else
    376 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset + 0,
    377 		    (value >> 0) & 0xffffffff);
    378 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset + 4,
    379 		    (value >> 32) & 0xffffffff);
    380 #endif
    381 	} else {
    382 		bus_space_write_4(sc->sc_iot, sc->sc_rbh, offset, value);
    383 	}
    384 }
    385 
    386 #if 0 /* unused */
    387 static inline uint32_t
    388 xhci_db_read_4(const struct xhci_softc * const sc, bus_size_t offset)
    389 {
    390 	return bus_space_read_4(sc->sc_iot, sc->sc_dbh, offset);
    391 }
    392 #endif /* unused */
    393 
    394 static inline void
    395 xhci_db_write_4(const struct xhci_softc * const sc, bus_size_t offset,
    396     uint32_t value)
    397 {
    398 	bus_space_write_4(sc->sc_iot, sc->sc_dbh, offset, value);
    399 }
    400 
    401 /* --- */
    402 
    403 static inline uint8_t
    404 xhci_ep_get_type(usb_endpoint_descriptor_t * const ed)
    405 {
    406 	u_int eptype = 0;
    407 
    408 	switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
    409 	case UE_CONTROL:
    410 		eptype = 0x0;
    411 		break;
    412 	case UE_ISOCHRONOUS:
    413 		eptype = 0x1;
    414 		break;
    415 	case UE_BULK:
    416 		eptype = 0x2;
    417 		break;
    418 	case UE_INTERRUPT:
    419 		eptype = 0x3;
    420 		break;
    421 	}
    422 
    423 	if ((UE_GET_XFERTYPE(ed->bmAttributes) == UE_CONTROL) ||
    424 	    (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN))
    425 		return eptype | 0x4;
    426 	else
    427 		return eptype;
    428 }
    429 
    430 static u_int
    431 xhci_ep_get_dci(usb_endpoint_descriptor_t * const ed)
    432 {
    433 	/* xHCI 1.0 section 4.5.1 */
    434 	u_int epaddr = UE_GET_ADDR(ed->bEndpointAddress);
    435 	u_int in = 0;
    436 
    437 	if ((UE_GET_XFERTYPE(ed->bmAttributes) == UE_CONTROL) ||
    438 	    (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN))
    439 		in = 1;
    440 
    441 	return epaddr * 2 + in;
    442 }
    443 
    444 static inline u_int
    445 xhci_dci_to_ici(const u_int i)
    446 {
    447 	return i + 1;
    448 }
    449 
    450 static inline void *
    451 xhci_slot_get_dcv(struct xhci_softc * const sc, struct xhci_slot * const xs,
    452     const u_int dci)
    453 {
    454 	return KERNADDR(&xs->xs_dc_dma, sc->sc_ctxsz * dci);
    455 }
    456 
    457 #if 0 /* unused */
    458 static inline bus_addr_t
    459 xhci_slot_get_dcp(struct xhci_softc * const sc, struct xhci_slot * const xs,
    460     const u_int dci)
    461 {
    462 	return DMAADDR(&xs->xs_dc_dma, sc->sc_ctxsz * dci);
    463 }
    464 #endif /* unused */
    465 
    466 static inline void *
    467 xhci_slot_get_icv(struct xhci_softc * const sc, struct xhci_slot * const xs,
    468     const u_int ici)
    469 {
    470 	return KERNADDR(&xs->xs_ic_dma, sc->sc_ctxsz * ici);
    471 }
    472 
    473 static inline bus_addr_t
    474 xhci_slot_get_icp(struct xhci_softc * const sc, struct xhci_slot * const xs,
    475     const u_int ici)
    476 {
    477 	return DMAADDR(&xs->xs_ic_dma, sc->sc_ctxsz * ici);
    478 }
    479 
    480 static inline struct xhci_trb *
    481 xhci_ring_trbv(struct xhci_ring * const xr, u_int idx)
    482 {
    483 	return KERNADDR(&xr->xr_dma, XHCI_TRB_SIZE * idx);
    484 }
    485 
    486 static inline bus_addr_t
    487 xhci_ring_trbp(struct xhci_ring * const xr, u_int idx)
    488 {
    489 	return DMAADDR(&xr->xr_dma, XHCI_TRB_SIZE * idx);
    490 }
    491 
    492 static inline void
    493 xhci_trb_put(struct xhci_trb * const trb, uint64_t parameter, uint32_t status,
    494     uint32_t control)
    495 {
    496 	trb->trb_0 = parameter;
    497 	trb->trb_2 = status;
    498 	trb->trb_3 = control;
    499 }
    500 
    501 /* --- */
    502 
    503 void
    504 xhci_childdet(device_t self, device_t child)
    505 {
    506 	struct xhci_softc * const sc = device_private(self);
    507 
    508 	KASSERT(sc->sc_child == child);
    509 	if (child == sc->sc_child)
    510 		sc->sc_child = NULL;
    511 }
    512 
    513 int
    514 xhci_detach(struct xhci_softc *sc, int flags)
    515 {
    516 	int rv = 0;
    517 
    518 	if (sc->sc_child != NULL)
    519 		rv = config_detach(sc->sc_child, flags);
    520 
    521 	if (rv != 0)
    522 		return rv;
    523 
    524 	/* XXX unconfigure/free slots */
    525 
    526 	/* verify: */
    527 	xhci_rt_write_4(sc, XHCI_IMAN(0), 0);
    528 	xhci_op_write_4(sc, XHCI_USBCMD, 0);
    529 	/* do we need to wait for stop? */
    530 
    531 	xhci_op_write_8(sc, XHCI_CRCR, 0);
    532 	xhci_ring_free(sc, &sc->sc_cr);
    533 	cv_destroy(&sc->sc_command_cv);
    534 
    535 	xhci_rt_write_4(sc, XHCI_ERSTSZ(0), 0);
    536 	xhci_rt_write_8(sc, XHCI_ERSTBA(0), 0);
    537 	xhci_rt_write_8(sc, XHCI_ERDP(0), 0|XHCI_ERDP_LO_BUSY);
    538 	xhci_ring_free(sc, &sc->sc_er);
    539 
    540 	usb_freemem(&sc->sc_bus, &sc->sc_eventst_dma);
    541 
    542 	xhci_op_write_8(sc, XHCI_DCBAAP, 0);
    543 	usb_freemem(&sc->sc_bus, &sc->sc_dcbaa_dma);
    544 
    545 	kmem_free(sc->sc_slots, sizeof(*sc->sc_slots) * sc->sc_maxslots);
    546 
    547 	mutex_destroy(&sc->sc_lock);
    548 	mutex_destroy(&sc->sc_intr_lock);
    549 	cv_destroy(&sc->sc_softwake_cv);
    550 
    551 	pool_cache_destroy(sc->sc_xferpool);
    552 
    553 	return rv;
    554 }
    555 
    556 int
    557 xhci_activate(device_t self, enum devact act)
    558 {
    559 	struct xhci_softc * const sc = device_private(self);
    560 
    561 	switch (act) {
    562 	case DVACT_DEACTIVATE:
    563 		sc->sc_dying = true;
    564 		return 0;
    565 	default:
    566 		return EOPNOTSUPP;
    567 	}
    568 }
    569 
    570 bool
    571 xhci_suspend(device_t dv, const pmf_qual_t *qual)
    572 {
    573 	return false;
    574 }
    575 
    576 bool
    577 xhci_resume(device_t dv, const pmf_qual_t *qual)
    578 {
    579 	return false;
    580 }
    581 
    582 bool
    583 xhci_shutdown(device_t self, int flags)
    584 {
    585 	return false;
    586 }
    587 
    588 
    589 static void
    590 hexdump(const char *msg, const void *base, size_t len)
    591 {
    592 #if 0
    593 	size_t cnt;
    594 	const uint32_t *p;
    595 	extern paddr_t vtophys(vaddr_t);
    596 
    597 	p = base;
    598 	cnt = 0;
    599 
    600 	printf("*** %s (%zu bytes @ %p %p)\n", msg, len, base,
    601 	    (void *)vtophys((vaddr_t)base));
    602 
    603 	while (cnt < len) {
    604 		if (cnt % 16 == 0)
    605 			printf("%p: ", p);
    606 		else if (cnt % 8 == 0)
    607 			printf(" |");
    608 		printf(" %08x", *p++);
    609 		cnt += 4;
    610 		if (cnt % 16 == 0)
    611 			printf("\n");
    612 	}
    613 #endif
    614 }
    615 
    616 
    617 int
    618 xhci_init(struct xhci_softc *sc)
    619 {
    620 	bus_size_t bsz;
    621 	uint32_t cap, hcs1, hcs2, hcc, dboff, rtsoff;
    622 	uint32_t ecp, ecr;
    623 	uint32_t usbcmd, usbsts, pagesize, config;
    624 	int i;
    625 	uint16_t hciversion;
    626 	uint8_t caplength;
    627 
    628 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
    629 
    630 	/* XXX Low/Full/High speeds for now */
    631 	sc->sc_bus.ub_revision = USBREV_2_0;
    632 	sc->sc_bus.ub_usedma = true;
    633 
    634 	cap = xhci_read_4(sc, XHCI_CAPLENGTH);
    635 	caplength = XHCI_CAP_CAPLENGTH(cap);
    636 	hciversion = XHCI_CAP_HCIVERSION(cap);
    637 
    638 	if ((hciversion < 0x0096) || (hciversion > 0x0100)) {
    639 		aprint_normal_dev(sc->sc_dev,
    640 		    "xHCI version %x.%x not known to be supported\n",
    641 		    (hciversion >> 8) & 0xff, (hciversion >> 0) & 0xff);
    642 	} else {
    643 		aprint_verbose_dev(sc->sc_dev, "xHCI version %x.%x\n",
    644 		    (hciversion >> 8) & 0xff, (hciversion >> 0) & 0xff);
    645 	}
    646 
    647 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, 0, caplength,
    648 	    &sc->sc_cbh) != 0) {
    649 		aprint_error_dev(sc->sc_dev, "capability subregion failure\n");
    650 		return ENOMEM;
    651 	}
    652 
    653 	hcs1 = xhci_cap_read_4(sc, XHCI_HCSPARAMS1);
    654 	sc->sc_maxslots = XHCI_HCS1_MAXSLOTS(hcs1);
    655 	sc->sc_maxintrs = XHCI_HCS1_MAXINTRS(hcs1);
    656 	sc->sc_maxports = XHCI_HCS1_MAXPORTS(hcs1);
    657 	hcs2 = xhci_cap_read_4(sc, XHCI_HCSPARAMS2);
    658 	(void)xhci_cap_read_4(sc, XHCI_HCSPARAMS3);
    659 	hcc = xhci_cap_read_4(sc, XHCI_HCCPARAMS);
    660 
    661 	sc->sc_ac64 = XHCI_HCC_AC64(hcc);
    662 	sc->sc_ctxsz = XHCI_HCC_CSZ(hcc) ? 64 : 32;
    663 	aprint_debug_dev(sc->sc_dev, "ac64 %d ctxsz %d\n", sc->sc_ac64,
    664 	    sc->sc_ctxsz);
    665 
    666 	aprint_debug_dev(sc->sc_dev, "xECP %x\n", XHCI_HCC_XECP(hcc) * 4);
    667 	ecp = XHCI_HCC_XECP(hcc) * 4;
    668 	while (ecp != 0) {
    669 		ecr = xhci_read_4(sc, ecp);
    670 		aprint_debug_dev(sc->sc_dev, "ECR %x: %08x\n", ecp, ecr);
    671 		switch (XHCI_XECP_ID(ecr)) {
    672 		case XHCI_ID_PROTOCOLS: {
    673 			uint32_t w0, w4, w8;
    674 			uint16_t w2;
    675 			w0 = xhci_read_4(sc, ecp + 0);
    676 			w2 = (w0 >> 16) & 0xffff;
    677 			w4 = xhci_read_4(sc, ecp + 4);
    678 			w8 = xhci_read_4(sc, ecp + 8);
    679 			aprint_debug_dev(sc->sc_dev, "SP: %08x %08x %08x\n",
    680 			    w0, w4, w8);
    681 			if (w4 == 0x20425355 && w2 == 0x0300) {
    682 				sc->sc_ss_port_start = (w8 >> 0) & 0xff;;
    683 				sc->sc_ss_port_count = (w8 >> 8) & 0xff;;
    684 			}
    685 			if (w4 == 0x20425355 && w2 == 0x0200) {
    686 				sc->sc_hs_port_start = (w8 >> 0) & 0xff;
    687 				sc->sc_hs_port_count = (w8 >> 8) & 0xff;
    688 			}
    689 			break;
    690 		}
    691 		case XHCI_ID_USB_LEGACY: {
    692 			uint8_t bios_sem;
    693 
    694 			/* Take host controller from BIOS */
    695 			bios_sem = xhci_read_1(sc, ecp + XHCI_XECP_BIOS_SEM);
    696 			if (bios_sem) {
    697 				/* sets xHCI to be owned by OS */
    698 				xhci_write_1(sc, ecp + XHCI_XECP_OS_SEM, 1);
    699 				aprint_debug(
    700 				    "waiting for BIOS to give up control\n");
    701 				for (i = 0; i < 5000; i++) {
    702 					bios_sem = xhci_read_1(sc, ecp +
    703 					    XHCI_XECP_BIOS_SEM);
    704 					if (bios_sem == 0)
    705 						break;
    706 					DELAY(1000);
    707 				}
    708 				if (bios_sem)
    709 					printf("timed out waiting for BIOS\n");
    710 			}
    711 			break;
    712 		}
    713 		default:
    714 			break;
    715 		}
    716 		ecr = xhci_read_4(sc, ecp);
    717 		if (XHCI_XECP_NEXT(ecr) == 0) {
    718 			ecp = 0;
    719 		} else {
    720 			ecp += XHCI_XECP_NEXT(ecr) * 4;
    721 		}
    722 	}
    723 
    724 	bsz = XHCI_PORTSC(sc->sc_maxports + 1);
    725 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, caplength, bsz,
    726 	    &sc->sc_obh) != 0) {
    727 		aprint_error_dev(sc->sc_dev, "operational subregion failure\n");
    728 		return ENOMEM;
    729 	}
    730 
    731 	dboff = xhci_cap_read_4(sc, XHCI_DBOFF);
    732 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, dboff,
    733 	    sc->sc_maxslots * 4, &sc->sc_dbh) != 0) {
    734 		aprint_error_dev(sc->sc_dev, "doorbell subregion failure\n");
    735 		return ENOMEM;
    736 	}
    737 
    738 	rtsoff = xhci_cap_read_4(sc, XHCI_RTSOFF);
    739 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh, rtsoff,
    740 	    sc->sc_maxintrs * 0x20, &sc->sc_rbh) != 0) {
    741 		aprint_error_dev(sc->sc_dev, "runtime subregion failure\n");
    742 		return ENOMEM;
    743 	}
    744 
    745 	for (i = 0; i < 100; i++) {
    746 		usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
    747 		if ((usbsts & XHCI_STS_CNR) == 0)
    748 			break;
    749 		usb_delay_ms(&sc->sc_bus, 1);
    750 	}
    751 	if (i >= 100)
    752 		return EIO;
    753 
    754 	usbcmd = 0;
    755 	xhci_op_write_4(sc, XHCI_USBCMD, usbcmd);
    756 	usb_delay_ms(&sc->sc_bus, 1);
    757 
    758 	usbcmd = XHCI_CMD_HCRST;
    759 	xhci_op_write_4(sc, XHCI_USBCMD, usbcmd);
    760 	for (i = 0; i < 100; i++) {
    761 		usbcmd = xhci_op_read_4(sc, XHCI_USBCMD);
    762 		if ((usbcmd & XHCI_CMD_HCRST) == 0)
    763 			break;
    764 		usb_delay_ms(&sc->sc_bus, 1);
    765 	}
    766 	if (i >= 100)
    767 		return EIO;
    768 
    769 	for (i = 0; i < 100; i++) {
    770 		usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
    771 		if ((usbsts & XHCI_STS_CNR) == 0)
    772 			break;
    773 		usb_delay_ms(&sc->sc_bus, 1);
    774 	}
    775 	if (i >= 100)
    776 		return EIO;
    777 
    778 	pagesize = xhci_op_read_4(sc, XHCI_PAGESIZE);
    779 	aprint_debug_dev(sc->sc_dev, "PAGESIZE 0x%08x\n", pagesize);
    780 	pagesize = ffs(pagesize);
    781 	if (pagesize == 0)
    782 		return EIO;
    783 	sc->sc_pgsz = 1 << (12 + (pagesize - 1));
    784 	aprint_debug_dev(sc->sc_dev, "sc_pgsz 0x%08x\n", (uint32_t)sc->sc_pgsz);
    785 	aprint_debug_dev(sc->sc_dev, "sc_maxslots 0x%08x\n",
    786 	    (uint32_t)sc->sc_maxslots);
    787 	aprint_debug_dev(sc->sc_dev, "sc_maxports %d\n", sc->sc_maxports);
    788 
    789 	usbd_status err;
    790 
    791 	sc->sc_maxspbuf = XHCI_HCS2_MAXSPBUF(hcs2);
    792 	aprint_debug_dev(sc->sc_dev, "sc_maxspbuf %d\n", sc->sc_maxspbuf);
    793 	if (sc->sc_maxspbuf != 0) {
    794 		err = usb_allocmem(&sc->sc_bus,
    795 		    sizeof(uint64_t) * sc->sc_maxspbuf, sizeof(uint64_t),
    796 		    &sc->sc_spbufarray_dma);
    797 		if (err)
    798 			return err;
    799 
    800 		sc->sc_spbuf_dma = kmem_zalloc(sizeof(*sc->sc_spbuf_dma) * sc->sc_maxspbuf, KM_SLEEP);
    801 		uint64_t *spbufarray = KERNADDR(&sc->sc_spbufarray_dma, 0);
    802 		for (i = 0; i < sc->sc_maxspbuf; i++) {
    803 			usb_dma_t * const dma = &sc->sc_spbuf_dma[i];
    804 			/* allocate contexts */
    805 			err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz,
    806 			    sc->sc_pgsz, dma);
    807 			if (err)
    808 				return err;
    809 			spbufarray[i] = htole64(DMAADDR(dma, 0));
    810 			usb_syncmem(dma, 0, sc->sc_pgsz,
    811 			    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
    812 		}
    813 
    814 		usb_syncmem(&sc->sc_spbufarray_dma, 0,
    815 		    sizeof(uint64_t) * sc->sc_maxspbuf, BUS_DMASYNC_PREWRITE);
    816 	}
    817 
    818 	config = xhci_op_read_4(sc, XHCI_CONFIG);
    819 	config &= ~0xFF;
    820 	config |= sc->sc_maxslots & 0xFF;
    821 	xhci_op_write_4(sc, XHCI_CONFIG, config);
    822 
    823 	err = xhci_ring_init(sc, &sc->sc_cr, XHCI_COMMAND_RING_TRBS,
    824 	    XHCI_COMMAND_RING_SEGMENTS_ALIGN);
    825 	if (err) {
    826 		aprint_error_dev(sc->sc_dev, "command ring init fail\n");
    827 		return err;
    828 	}
    829 
    830 	err = xhci_ring_init(sc, &sc->sc_er, XHCI_EVENT_RING_TRBS,
    831 	    XHCI_EVENT_RING_SEGMENTS_ALIGN);
    832 	if (err) {
    833 		aprint_error_dev(sc->sc_dev, "event ring init fail\n");
    834 		return err;
    835 	}
    836 
    837 	usb_dma_t *dma;
    838 	size_t size;
    839 	size_t align;
    840 
    841 	dma = &sc->sc_eventst_dma;
    842 	size = roundup2(XHCI_EVENT_RING_SEGMENTS * XHCI_ERSTE_SIZE,
    843 	    XHCI_EVENT_RING_SEGMENT_TABLE_ALIGN);
    844 	KASSERT(size <= (512 * 1024));
    845 	align = XHCI_EVENT_RING_SEGMENT_TABLE_ALIGN;
    846 	err = usb_allocmem(&sc->sc_bus, size, align, dma);
    847 
    848 	memset(KERNADDR(dma, 0), 0, size);
    849 	usb_syncmem(dma, 0, size, BUS_DMASYNC_PREWRITE);
    850 	aprint_debug_dev(sc->sc_dev, "eventst: %s %016jx %p %zx\n",
    851 	    usbd_errstr(err),
    852 	    (uintmax_t)DMAADDR(&sc->sc_eventst_dma, 0),
    853 	    KERNADDR(&sc->sc_eventst_dma, 0),
    854 	    sc->sc_eventst_dma.udma_block->size);
    855 
    856 	dma = &sc->sc_dcbaa_dma;
    857 	size = (1 + sc->sc_maxslots) * sizeof(uint64_t);
    858 	KASSERT(size <= 2048);
    859 	align = XHCI_DEVICE_CONTEXT_BASE_ADDRESS_ARRAY_ALIGN;
    860 	err = usb_allocmem(&sc->sc_bus, size, align, dma);
    861 
    862 	memset(KERNADDR(dma, 0), 0, size);
    863 	if (sc->sc_maxspbuf != 0) {
    864 		/*
    865 		 * DCBA entry 0 hold the scratchbuf array pointer.
    866 		 */
    867 		*(uint64_t *)KERNADDR(dma, 0) =
    868 		    htole64(DMAADDR(&sc->sc_spbufarray_dma, 0));
    869 	}
    870 	usb_syncmem(dma, 0, size, BUS_DMASYNC_PREWRITE);
    871 	aprint_debug_dev(sc->sc_dev, "dcbaa: %s %016jx %p %zx\n",
    872 	    usbd_errstr(err),
    873 	    (uintmax_t)DMAADDR(&sc->sc_dcbaa_dma, 0),
    874 	    KERNADDR(&sc->sc_dcbaa_dma, 0),
    875 	    sc->sc_dcbaa_dma.udma_block->size);
    876 
    877 	sc->sc_slots = kmem_zalloc(sizeof(*sc->sc_slots) * sc->sc_maxslots,
    878 	    KM_SLEEP);
    879 
    880 	cv_init(&sc->sc_command_cv, "xhcicmd");
    881 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
    882 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_SCHED);
    883 	cv_init(&sc->sc_softwake_cv, "xhciab");
    884 
    885 	sc->sc_xferpool = pool_cache_init(sizeof(struct xhci_xfer), 0, 0, 0,
    886 	    "xhcixfer", NULL, IPL_USB, NULL, NULL, NULL);
    887 
    888 	/* Set up the bus struct. */
    889 	sc->sc_bus.ub_methods = &xhci_bus_methods;
    890 	sc->sc_bus.ub_pipesize = sizeof(struct xhci_pipe);
    891 
    892 	struct xhci_erste *erst;
    893 	erst = KERNADDR(&sc->sc_eventst_dma, 0);
    894 	erst[0].erste_0 = htole64(xhci_ring_trbp(&sc->sc_er, 0));
    895 	erst[0].erste_2 = htole32(XHCI_EVENT_RING_TRBS);
    896 	erst[0].erste_3 = htole32(0);
    897 	usb_syncmem(&sc->sc_eventst_dma, 0,
    898 	    XHCI_ERSTE_SIZE * XHCI_EVENT_RING_SEGMENTS, BUS_DMASYNC_PREWRITE);
    899 
    900 	xhci_rt_write_4(sc, XHCI_ERSTSZ(0), XHCI_EVENT_RING_SEGMENTS);
    901 	xhci_rt_write_8(sc, XHCI_ERSTBA(0), DMAADDR(&sc->sc_eventst_dma, 0));
    902 	xhci_rt_write_8(sc, XHCI_ERDP(0), xhci_ring_trbp(&sc->sc_er, 0) |
    903 	    XHCI_ERDP_LO_BUSY);
    904 	xhci_op_write_8(sc, XHCI_DCBAAP, DMAADDR(&sc->sc_dcbaa_dma, 0));
    905 	xhci_op_write_8(sc, XHCI_CRCR, xhci_ring_trbp(&sc->sc_cr, 0) |
    906 	    sc->sc_cr.xr_cs);
    907 
    908 #if 0
    909 	hexdump("eventst", KERNADDR(&sc->sc_eventst_dma, 0),
    910 	    XHCI_ERSTE_SIZE * XHCI_EVENT_RING_SEGMENTS);
    911 #endif
    912 
    913 	xhci_rt_write_4(sc, XHCI_IMAN(0), XHCI_IMAN_INTR_ENA);
    914 	if ((sc->sc_quirks & XHCI_QUIRK_INTEL) != 0)
    915 		/* Intel xhci needs interrupt rate moderated. */
    916 		xhci_rt_write_4(sc, XHCI_IMOD(0), XHCI_IMOD_DEFAULT_LP);
    917 	else
    918 		xhci_rt_write_4(sc, XHCI_IMOD(0), 0);
    919 	aprint_debug_dev(sc->sc_dev, "setting IMOD %u\n",
    920 	    xhci_rt_read_4(sc, XHCI_IMOD(0)));
    921 
    922 	xhci_op_write_4(sc, XHCI_USBCMD, XHCI_CMD_INTE|XHCI_CMD_RS); /* Go! */
    923 	aprint_debug_dev(sc->sc_dev, "USBCMD %08"PRIx32"\n",
    924 	    xhci_op_read_4(sc, XHCI_USBCMD));
    925 
    926 	return USBD_NORMAL_COMPLETION;
    927 }
    928 
    929 int
    930 xhci_intr(void *v)
    931 {
    932 	struct xhci_softc * const sc = v;
    933 	int ret = 0;
    934 
    935 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
    936 
    937 	if (sc == NULL)
    938 		return 0;
    939 
    940 	mutex_spin_enter(&sc->sc_intr_lock);
    941 
    942 	if (sc->sc_dying || !device_has_power(sc->sc_dev))
    943 		goto done;
    944 
    945 	/* If we get an interrupt while polling, then just ignore it. */
    946 	if (sc->sc_bus.ub_usepolling) {
    947 #ifdef DIAGNOSTIC
    948 		DPRINTFN(16, "ignored interrupt while polling", 0, 0, 0, 0);
    949 #endif
    950 		goto done;
    951 	}
    952 
    953 	ret = xhci_intr1(sc);
    954 done:
    955 	mutex_spin_exit(&sc->sc_intr_lock);
    956 	return ret;
    957 }
    958 
    959 int
    960 xhci_intr1(struct xhci_softc * const sc)
    961 {
    962 	uint32_t usbsts;
    963 	uint32_t iman;
    964 
    965 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
    966 
    967 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
    968 	DPRINTFN(16, "USBSTS %08x", usbsts, 0, 0, 0);
    969 #if 0
    970 	if ((usbsts & (XHCI_STS_EINT|XHCI_STS_PCD)) == 0) {
    971 		return 0;
    972 	}
    973 #endif
    974 	xhci_op_write_4(sc, XHCI_USBSTS,
    975 	    usbsts & (2|XHCI_STS_EINT|XHCI_STS_PCD)); /* XXX */
    976 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
    977 	DPRINTFN(16, "USBSTS %08x", usbsts, 0, 0, 0);
    978 
    979 	iman = xhci_rt_read_4(sc, XHCI_IMAN(0));
    980 	DPRINTFN(16, "IMAN0 %08x", iman, 0, 0, 0);
    981 
    982 	if (!(sc->sc_quirks & XHCI_QUIRK_FORCE_INTR)) {
    983 		if ((iman & XHCI_IMAN_INTR_PEND) == 0) {
    984 			return 0;
    985 		}
    986 	}
    987 
    988 	xhci_rt_write_4(sc, XHCI_IMAN(0), iman);
    989 	iman = xhci_rt_read_4(sc, XHCI_IMAN(0));
    990 	DPRINTFN(16, "IMAN0 %08x", iman, 0, 0, 0);
    991 	usbsts = xhci_op_read_4(sc, XHCI_USBSTS);
    992 	DPRINTFN(16, "USBSTS %08x", usbsts, 0, 0, 0);
    993 
    994 	usb_schedsoftintr(&sc->sc_bus);
    995 
    996 	return 1;
    997 }
    998 
    999 /*
   1000  * 3 port speed types used in USB stack
   1001  *
   1002  * usbdi speed
   1003  *	definition: USB_SPEED_* in usb.h
   1004  *	They are used in struct usbd_device in USB stack.
   1005  *	ioctl interface uses these values too.
   1006  * port_status speed
   1007  *	definition: UPS_*_SPEED in usb.h
   1008  *	They are used in usb_port_status_t and valid only for USB 2.0.
   1009  *	Speed value is always 0 for Super Speed or more, and dwExtPortStatus
   1010  *	of usb_port_status_ext_t indicates port speed.
   1011  *	Note that some 3.0 values overlap with 2.0 values.
   1012  *	(e.g. 0x200 means UPS_POER_POWER_SS in SS and
   1013  *	            means UPS_LOW_SPEED in HS.)
   1014  *	port status returned from hub also uses these values.
   1015  *	On NetBSD UPS_OTHER_SPEED indicates port speed is super speed
   1016  *	or more.
   1017  * xspeed:
   1018  *	definition: Protocol Speed ID (PSI) (xHCI 1.1 7.2.1)
   1019  *	They are used in only slot context and PORTSC reg of xhci.
   1020  *	The difference between usbdi speed and xspeed is
   1021  *	that FS and LS values are swapped.
   1022  */
   1023 
   1024 /* convert usbdi speed to xspeed */
   1025 static int
   1026 xhci_speed2xspeed(int speed)
   1027 {
   1028 	switch (speed) {
   1029 	case USB_SPEED_LOW:	return 2;
   1030 	case USB_SPEED_FULL:	return 1;
   1031 	default:		return speed;
   1032 	}
   1033 }
   1034 
   1035 /* convert xspeed to usbdi speed */
   1036 static int
   1037 xhci_xspeed2speed(int xspeed)
   1038 {
   1039 	switch (xspeed) {
   1040 	case 1: return USB_SPEED_FULL;
   1041 	case 2: return USB_SPEED_LOW;
   1042 	default: return xspeed;
   1043 	}
   1044 }
   1045 
   1046 /* convert xspeed to port status speed */
   1047 static int
   1048 xhci_xspeed2psspeed(int xspeed)
   1049 {
   1050 	switch (xspeed) {
   1051 	case 0: return 0;
   1052 	case 1: return UPS_FULL_SPEED;
   1053 	case 2: return UPS_LOW_SPEED;
   1054 	case 3: return UPS_HIGH_SPEED;
   1055 	default: return UPS_OTHER_SPEED;
   1056 	}
   1057 }
   1058 
   1059 /* construct slot context */
   1060 static void
   1061 xhci_setup_sctx(struct usbd_device *dev, uint32_t *cp)
   1062 {
   1063 	usb_device_descriptor_t * const dd = &dev->ud_ddesc;
   1064 	int speed = dev->ud_speed;
   1065 	int tthubslot, ttportnum;
   1066 	bool ishub;
   1067 	bool usemtt;
   1068 
   1069 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1070 
   1071 	/* 6.2.2 */
   1072 	/*
   1073 	 * tthubslot:
   1074 	 *   This is the slot ID of parent HS hub
   1075 	 *   if LS/FS device is connected && connected through HS hub.
   1076 	 *   This is 0 if device is not LS/FS device ||
   1077 	 *   parent hub is not HS hub ||
   1078 	 *   attached to root hub.
   1079 	 * ttportnum:
   1080 	 *   This is the downstream facing port of parent HS hub
   1081 	 *   if LS/FS device is connected.
   1082 	 *   This is 0 if device is not LS/FS device ||
   1083 	 *   parent hub is not HS hub ||
   1084 	 *   attached to root hub.
   1085 	 */
   1086 	if (dev->ud_myhsport != NULL &&
   1087 	    dev->ud_myhub != NULL && dev->ud_myhub->ud_depth != 0 &&
   1088 	    (dev->ud_myhub != NULL &&
   1089 	     dev->ud_myhub->ud_speed == USB_SPEED_HIGH) &&
   1090 	    (speed == USB_SPEED_LOW || speed == USB_SPEED_FULL)) {
   1091 		ttportnum = dev->ud_myhsport->up_portno;
   1092 		/* XXX addr == slot ? */
   1093 		tthubslot = dev->ud_myhsport->up_parent->ud_addr;
   1094 	} else {
   1095 		ttportnum = 0;
   1096 		tthubslot = 0;
   1097 	}
   1098 	DPRINTFN(4, "myhsport %p ttportnum=%d tthubslot=%d",
   1099 	    dev->ud_myhsport, ttportnum, tthubslot, 0);
   1100 
   1101 	/* ishub is valid after reading UDESC_DEVICE */
   1102 	ishub = (dd->bDeviceClass == UDCLASS_HUB);
   1103 
   1104 	/* dev->ud_hub is valid after reading UDESC_HUB */
   1105 	if (ishub && dev->ud_hub) {
   1106 		usb_hub_descriptor_t *hd = &dev->ud_hub->uh_hubdesc;
   1107 
   1108 		cp[1] |= htole32(XHCI_SCTX_1_NUM_PORTS_SET(hd->bNbrPorts));
   1109 		cp[2] |= htole32(XHCI_SCTX_2_TT_THINK_TIME_SET(
   1110 		    __SHIFTOUT(UGETW(hd->wHubCharacteristics), UHD_TT_THINK)));
   1111 		DPRINTFN(4, "nports=%d ttt=%d",
   1112 		    hd->bNbrPorts, XHCI_SCTX_2_TT_THINK_TIME_GET(cp[2]), 0, 0);
   1113 	}
   1114 
   1115 #define IS_TTHUB(dd) \
   1116     ((dd)->bDeviceProtocol == UDPROTO_HSHUBSTT || \
   1117      (dd)->bDeviceProtocol == UDPROTO_HSHUBMTT)
   1118 
   1119 	/*
   1120 	 * MTT flag is set if
   1121 	 * 1. this is HS hub && MTT is enabled
   1122 	 *  or
   1123 	 * 2. this is not hub && this is LS or FS device &&
   1124 	 *    MTT of parent HS hub (and its parent, too) is enabled
   1125 	 */
   1126 	if (ishub && speed == USB_SPEED_HIGH && IS_TTHUB(dd))
   1127 		usemtt = true;
   1128 	else if (!ishub &&
   1129 	     (speed == USB_SPEED_LOW || speed == USB_SPEED_FULL) &&
   1130 	     dev->ud_myhub != NULL && dev->ud_myhub->ud_depth != 0 &&
   1131 	     (dev->ud_myhub != NULL &&
   1132 	      dev->ud_myhub->ud_speed == USB_SPEED_HIGH) &&
   1133 	     dev->ud_myhsport != NULL &&
   1134 	     IS_TTHUB(&dev->ud_myhsport->up_parent->ud_ddesc))
   1135 		usemtt = true;
   1136 	else
   1137 		usemtt = false;
   1138 	DPRINTFN(4, "class %u proto %u ishub %d usemtt %d",
   1139 	    dd->bDeviceClass, dd->bDeviceProtocol, ishub, usemtt);
   1140 
   1141 	cp[0] |= htole32(
   1142 	    XHCI_SCTX_0_SPEED_SET(xhci_speed2xspeed(speed)) |
   1143 	    XHCI_SCTX_0_HUB_SET(ishub ? 1 : 0) |
   1144 	    XHCI_SCTX_0_MTT_SET(usemtt ? 1 : 0)
   1145 	    );
   1146 	cp[1] |= htole32(0);
   1147 	cp[2] |= htole32(
   1148 	    XHCI_SCTX_2_IRQ_TARGET_SET(0) |
   1149 	    XHCI_SCTX_2_TT_HUB_SID_SET(tthubslot) |
   1150 	    XHCI_SCTX_2_TT_PORT_NUM_SET(ttportnum)
   1151 	    );
   1152 	cp[3] |= htole32(0);
   1153 }
   1154 
   1155 /*
   1156  * called
   1157  *  from xhci_open
   1158  *  from usbd_setup_pipe_flags
   1159  *  from usbd_open_pipe_ival
   1160  */
   1161 static usbd_status
   1162 xhci_configure_endpoint(struct usbd_pipe *pipe)
   1163 {
   1164 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   1165 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1166 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
   1167 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
   1168 	const uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
   1169 	struct xhci_trb trb;
   1170 	usbd_status err;
   1171 	uint32_t *cp;
   1172 	uint32_t mps = UGETW(ed->wMaxPacketSize);
   1173 	uint32_t maxb = 0;
   1174 	int speed = pipe->up_dev->ud_speed;
   1175 	uint32_t ival = ed->bInterval;
   1176 
   1177 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1178 	DPRINTFN(4, "slot %u dci %u epaddr 0x%02x attr 0x%02x",
   1179 	    xs->xs_idx, dci, ed->bEndpointAddress, ed->bmAttributes);
   1180 
   1181 	/* XXX ensure input context is available? */
   1182 
   1183 	memset(xhci_slot_get_icv(sc, xs, 0), 0, sc->sc_pgsz);
   1184 
   1185 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
   1186 	cp[0] = htole32(0);
   1187 	cp[1] = htole32(XHCI_INCTX_1_ADD_MASK(dci));
   1188 
   1189 	/* set up input slot context */
   1190 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_SLOT));
   1191 	xhci_setup_sctx(pipe->up_dev, cp);
   1192 	cp[0] |= htole32(XHCI_SCTX_0_CTX_NUM_SET(dci));
   1193 
   1194 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(dci));
   1195 	cp[0] = htole32(
   1196 	    XHCI_EPCTX_0_EPSTATE_SET(0) |
   1197 	    XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
   1198 	    XHCI_EPCTX_0_LSA_SET(0)
   1199 	    );
   1200 	cp[1] = htole32(
   1201 	    XHCI_EPCTX_1_EPTYPE_SET(xhci_ep_get_type(ed)) |
   1202 	    XHCI_EPCTX_1_MAXB_SET(0)
   1203 	    );
   1204 	if (xfertype != UE_ISOCHRONOUS)
   1205 		cp[1] |= htole32(XHCI_EPCTX_1_CERR_SET(3));
   1206 
   1207 	if (USB_IS_SS(speed)) {
   1208 		usbd_desc_iter_t iter;
   1209 		const usb_cdc_descriptor_t *cdcd;
   1210 		const usb_endpoint_ss_comp_descriptor_t * esscd = NULL;
   1211 		uint8_t ep;
   1212 
   1213 		cdcd = (const usb_cdc_descriptor_t *)usb_find_desc(
   1214 		    pipe->up_dev, UDESC_INTERFACE, USBD_CDCSUBTYPE_ANY);
   1215 		usb_desc_iter_init(pipe->up_dev, &iter);
   1216 		iter.cur = (const void *)cdcd;
   1217 
   1218 		/* find endpoint_ss_comp desc for ep of this pipe */
   1219 		for(ep = 0;;) {
   1220 			cdcd = (const usb_cdc_descriptor_t *)
   1221 			    usb_desc_iter_next(&iter);
   1222 			if (cdcd == NULL)
   1223 				break;
   1224 			if (ep == 0 &&
   1225 			    cdcd->bDescriptorType == UDESC_ENDPOINT) {
   1226 				ep = ((const usb_endpoint_descriptor_t *)cdcd)->
   1227 				    bEndpointAddress;
   1228 				if (UE_GET_ADDR(ep) ==
   1229 				    UE_GET_ADDR(ed->bEndpointAddress)) {
   1230 					cdcd = (const usb_cdc_descriptor_t *)
   1231 					    usb_desc_iter_next(&iter);
   1232 					break;
   1233 				}
   1234 				ep = 0;
   1235 			}
   1236 		}
   1237 		if (cdcd != NULL &&
   1238 		    cdcd->bDescriptorType == UDESC_ENDPOINT_SS_COMP) {
   1239 			esscd = (const usb_endpoint_ss_comp_descriptor_t *)cdcd;
   1240 			maxb = esscd->bMaxBurst;
   1241 			cp[1] |= htole32(XHCI_EPCTX_1_MAXB_SET(maxb));
   1242 			DPRINTFN(4, "setting SS MaxBurst %u", maxb, 0, 0, 0);
   1243 		}
   1244 	}
   1245 	if (speed == USB_SPEED_HIGH &&
   1246 	    (xfertype == UE_ISOCHRONOUS || xfertype == UE_INTERRUPT)) {
   1247 		maxb = UE_GET_TRANS(UGETW(ed->wMaxPacketSize));
   1248 		cp[1] |= htole32(XHCI_EPCTX_1_MAXB_SET(maxb));
   1249 		DPRINTFN(4, "setting HS MaxBurst %u", maxb, 0, 0, 0);
   1250 	}
   1251 
   1252 	switch (xfertype) {
   1253 	case UE_INTERRUPT:
   1254 		if (pipe->up_interval != USBD_DEFAULT_INTERVAL)
   1255 			ival = pipe->up_interval;
   1256 
   1257 		/* xHCI 6.2.3.6 Table 65, USB 2.0 9.6.6 */
   1258 		if (speed == USB_SPEED_LOW || speed == USB_SPEED_FULL) {
   1259 			int i;
   1260 
   1261 			/*
   1262 			 * round ival down to "the nearest base 2 multiple of
   1263 			 * bInterval * 8".
   1264 			 * bInterval is at most 255 as its type is uByte.
   1265 			 * 255(ms) = 2040(x 125us) < 2^11, so start with 11.
   1266 			 */
   1267 			for (i = 11; i > 0; i--) {
   1268 				if ((ival * 8) >= (1 << i))
   1269 					break;
   1270 			}
   1271 			ival = i;
   1272 		} else {
   1273 			/* Interval = bInterval-1 for SS/HS */
   1274 			ival--;
   1275 		}
   1276 		DPRINTFN(4, "ival %u", ival, 0, 0, 0);
   1277 
   1278 		if (USB_IS_SS(speed)) {
   1279 			if (maxb > 0)
   1280 				mps = 1024;
   1281 		} else {
   1282 			mps = mps ? mps : 8;
   1283 		}
   1284 		cp[0] |= htole32(XHCI_EPCTX_0_IVAL_SET(ival));
   1285 		cp[1] |= htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
   1286 		cp[4] = htole32(
   1287 		    XHCI_EPCTX_4_AVG_TRB_LEN_SET(8) /* XXX */
   1288 		    );
   1289 		break;
   1290 	case UE_CONTROL:
   1291 		if (USB_IS_SS(speed))
   1292 			mps = 512;
   1293 		else
   1294 			mps = mps ? mps : 8;
   1295 		cp[1] |= htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
   1296 		cp[4] = htole32(XHCI_EPCTX_4_AVG_TRB_LEN_SET(8)); /* XXX */
   1297 		break;
   1298 #ifdef notyet
   1299 	case UE_ISOCHRONOUS:
   1300 		if (speed == USB_SPEED_FULL)
   1301 			ival += 3; /* 1ms -> 125us */
   1302 		ival--;
   1303 		DPRINTFN(4, "ival %u", ival, 0, 0, 0);
   1304 
   1305 		if (USB_IS_SS(speed)) {
   1306 			mps = 1024;
   1307 		} else {
   1308 			mps = mps ? mps : 1024;
   1309 		}
   1310 		cp[1] |= htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
   1311 		cp[4] = htole32(XHCI_EPCTX_4_AVG_TRB_LEN_SET(1024)); /* XXX */
   1312 		break;
   1313 #endif
   1314 	default:
   1315 		if (USB_IS_SS(speed))
   1316 			mps = 1024;
   1317 		else
   1318 			mps = mps ? mps : 512;
   1319 		cp[1] |= htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
   1320 		cp[4] = htole32(XHCI_EPCTX_4_AVG_TRB_LEN_SET(1024)); /* XXX */
   1321 		break;
   1322 	}
   1323 	*(uint64_t *)(&cp[2]) = htole64(
   1324 	    xhci_ring_trbp(&xs->xs_ep[dci].xe_tr, 0) |
   1325 	    XHCI_EPCTX_2_DCS_SET(1));
   1326 
   1327 	/* sync input contexts before they are read from memory */
   1328 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
   1329 	hexdump("input control context", xhci_slot_get_icv(sc, xs, 0),
   1330 	    sc->sc_ctxsz * 1);
   1331 	hexdump("input endpoint context", xhci_slot_get_icv(sc, xs,
   1332 	    xhci_dci_to_ici(dci)), sc->sc_ctxsz * 1);
   1333 
   1334 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
   1335 	trb.trb_2 = 0;
   1336 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   1337 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP);
   1338 
   1339 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   1340 
   1341 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
   1342 	hexdump("output context", xhci_slot_get_dcv(sc, xs, dci),
   1343 	    sc->sc_ctxsz * 1);
   1344 
   1345 	return err;
   1346 }
   1347 
   1348 #if 0
   1349 static usbd_status
   1350 xhci_unconfigure_endpoint(struct usbd_pipe *pipe)
   1351 {
   1352 #ifdef USB_DEBUG
   1353 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1354 #endif
   1355 
   1356 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1357 	DPRINTFN(4, "slot %u", xs->xs_idx, 0, 0, 0);
   1358 
   1359 	return USBD_NORMAL_COMPLETION;
   1360 }
   1361 #endif
   1362 
   1363 /* 4.6.8, 6.4.3.7 */
   1364 static usbd_status
   1365 xhci_reset_endpoint(struct usbd_pipe *pipe)
   1366 {
   1367 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   1368 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1369 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
   1370 	struct xhci_trb trb;
   1371 	usbd_status err;
   1372 
   1373 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1374 	DPRINTFN(4, "slot %u dci %u", xs->xs_idx, dci, 0, 0);
   1375 
   1376 	KASSERT(!mutex_owned(&sc->sc_lock));
   1377 
   1378 	trb.trb_0 = 0;
   1379 	trb.trb_2 = 0;
   1380 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   1381 	    XHCI_TRB_3_EP_SET(dci) |
   1382 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP);
   1383 
   1384 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   1385 
   1386 	return err;
   1387 }
   1388 
   1389 /*
   1390  * 4.6.9, 6.4.3.8
   1391  * Stop execution of TDs on xfer ring.
   1392  * Should be called with sc_lock held.
   1393  */
   1394 static usbd_status
   1395 xhci_stop_endpoint(struct usbd_pipe *pipe)
   1396 {
   1397 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   1398 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1399 	struct xhci_trb trb;
   1400 	usbd_status err;
   1401 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
   1402 
   1403 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1404 	DPRINTFN(4, "slot %u dci %u", xs->xs_idx, dci, 0, 0);
   1405 
   1406 	KASSERT(mutex_owned(&sc->sc_lock));
   1407 
   1408 	trb.trb_0 = 0;
   1409 	trb.trb_2 = 0;
   1410 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   1411 	    XHCI_TRB_3_EP_SET(dci) |
   1412 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP);
   1413 
   1414 	err = xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
   1415 
   1416 	return err;
   1417 }
   1418 
   1419 /*
   1420  * Set TR Dequeue Pointer.
   1421  * xCHI 1.1  4.6.10  6.4.3.9
   1422  * Purge all of the transfer requests on ring.
   1423  * EPSTATE of endpoint must be ERROR or STOPPED, or CONTEXT_STATE error.
   1424  */
   1425 static usbd_status
   1426 xhci_set_dequeue(struct usbd_pipe *pipe)
   1427 {
   1428 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   1429 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1430 	const u_int dci = xhci_ep_get_dci(pipe->up_endpoint->ue_edesc);
   1431 	struct xhci_ring * const xr = &xs->xs_ep[dci].xe_tr;
   1432 	struct xhci_trb trb;
   1433 	usbd_status err;
   1434 
   1435 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1436 	DPRINTFN(4, "slot %u dci %u", xs->xs_idx, dci, 0, 0);
   1437 
   1438 	memset(xr->xr_trb, 0, xr->xr_ntrb * XHCI_TRB_SIZE);
   1439 	usb_syncmem(&xr->xr_dma, 0, xr->xr_ntrb * XHCI_TRB_SIZE,
   1440 	    BUS_DMASYNC_PREWRITE);
   1441 
   1442 	xr->xr_ep = 0;
   1443 	xr->xr_cs = 1;
   1444 
   1445 	/* set DCS */
   1446 	trb.trb_0 = xhci_ring_trbp(xr, 0) | 1; /* XXX */
   1447 	trb.trb_2 = 0;
   1448 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   1449 	    XHCI_TRB_3_EP_SET(dci) |
   1450 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE);
   1451 
   1452 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   1453 
   1454 	return err;
   1455 }
   1456 
   1457 /*
   1458  * Open new pipe: called from usbd_setup_pipe_flags.
   1459  * Fills methods of pipe.
   1460  * If pipe is not for ep0, calls configure_endpoint.
   1461  */
   1462 static usbd_status
   1463 xhci_open(struct usbd_pipe *pipe)
   1464 {
   1465 	struct usbd_device * const dev = pipe->up_dev;
   1466 	struct xhci_softc * const sc = dev->ud_bus->ub_hcpriv;
   1467 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
   1468 	const uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
   1469 
   1470 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1471 	DPRINTFN(1, "addr %d depth %d port %d speed %d",
   1472 	    dev->ud_addr, dev->ud_depth, dev->ud_powersrc->up_portno,
   1473 	    dev->ud_speed);
   1474 
   1475 	if (sc->sc_dying)
   1476 		return USBD_IOERROR;
   1477 
   1478 	/* Root Hub */
   1479 	if (dev->ud_depth == 0 && dev->ud_powersrc->up_portno == 0) {
   1480 		switch (ed->bEndpointAddress) {
   1481 		case USB_CONTROL_ENDPOINT:
   1482 			pipe->up_methods = &roothub_ctrl_methods;
   1483 			break;
   1484 		case UE_DIR_IN | USBROOTHUB_INTR_ENDPT:
   1485 			pipe->up_methods = &xhci_root_intr_methods;
   1486 			break;
   1487 		default:
   1488 			pipe->up_methods = NULL;
   1489 			DPRINTFN(0, "bad bEndpointAddress 0x%02x",
   1490 			    ed->bEndpointAddress, 0, 0, 0);
   1491 			return USBD_INVAL;
   1492 		}
   1493 		return USBD_NORMAL_COMPLETION;
   1494 	}
   1495 
   1496 	switch (xfertype) {
   1497 	case UE_CONTROL:
   1498 		pipe->up_methods = &xhci_device_ctrl_methods;
   1499 		break;
   1500 	case UE_ISOCHRONOUS:
   1501 		pipe->up_methods = &xhci_device_isoc_methods;
   1502 		return USBD_INVAL;
   1503 		break;
   1504 	case UE_BULK:
   1505 		pipe->up_methods = &xhci_device_bulk_methods;
   1506 		break;
   1507 	case UE_INTERRUPT:
   1508 		pipe->up_methods = &xhci_device_intr_methods;
   1509 		break;
   1510 	default:
   1511 		return USBD_IOERROR;
   1512 		break;
   1513 	}
   1514 
   1515 	if (ed->bEndpointAddress != USB_CONTROL_ENDPOINT)
   1516 		return xhci_configure_endpoint(pipe);
   1517 
   1518 	return USBD_NORMAL_COMPLETION;
   1519 }
   1520 
   1521 /*
   1522  * Closes pipe, called from usbd_kill_pipe via close methods.
   1523  * If the endpoint to be closed is ep0, disable_slot.
   1524  * Should be called with sc_lock held.
   1525  */
   1526 static void
   1527 xhci_close_pipe(struct usbd_pipe *pipe)
   1528 {
   1529 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   1530 	struct xhci_slot * const xs = pipe->up_dev->ud_hcpriv;
   1531 	usb_endpoint_descriptor_t * const ed = pipe->up_endpoint->ue_edesc;
   1532 	const u_int dci = xhci_ep_get_dci(ed);
   1533 	struct xhci_trb trb;
   1534 	uint32_t *cp;
   1535 
   1536 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1537 
   1538 	if (sc->sc_dying)
   1539 		return;
   1540 
   1541 	if (xs == NULL || xs->xs_idx == 0)
   1542 		/* xs is uninitialized before xhci_init_slot */
   1543 		return;
   1544 
   1545 	DPRINTFN(4, "slot %u dci %u", xs->xs_idx, dci, 0, 0);
   1546 
   1547 	KASSERTMSG(!cpu_intr_p() && !cpu_softintr_p(), "called from intr ctx");
   1548 	KASSERT(mutex_owned(&sc->sc_lock));
   1549 
   1550 	if (pipe->up_dev->ud_depth == 0)
   1551 		return;
   1552 
   1553 	if (dci == XHCI_DCI_EP_CONTROL) {
   1554 		DPRINTFN(4, "closing ep0", 0, 0, 0, 0);
   1555 		xhci_disable_slot(sc, xs->xs_idx);
   1556 		return;
   1557 	}
   1558 
   1559 	/*
   1560 	 * This may fail in the case that xhci_close_pipe is called after
   1561 	 * xhci_abort_xfer e.g. usbd_kill_pipe.
   1562 	 */
   1563 	(void)xhci_stop_endpoint(pipe);
   1564 
   1565 	/*
   1566 	 * set appropriate bit to be dropped.
   1567 	 * don't set DC bit to 1, otherwise all endpoints
   1568 	 * would be deconfigured.
   1569 	 */
   1570 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
   1571 	cp[0] = htole32(XHCI_INCTX_0_DROP_MASK(dci));
   1572 	cp[1] = htole32(0);
   1573 
   1574 	/* XXX should be most significant one, not dci? */
   1575 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_SLOT));
   1576 	cp[0] = htole32(XHCI_SCTX_0_CTX_NUM_SET(dci));
   1577 
   1578 	/* sync input contexts before they are read from memory */
   1579 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
   1580 
   1581 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
   1582 	trb.trb_2 = 0;
   1583 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   1584 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP);
   1585 
   1586 	(void)xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   1587 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
   1588 }
   1589 
   1590 /*
   1591  * Abort transfer.
   1592  * Called with sc_lock held.
   1593  * May be called from softintr context.
   1594  */
   1595 static void
   1596 xhci_abort_xfer(struct usbd_xfer *xfer, usbd_status status)
   1597 {
   1598 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   1599 
   1600 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1601 	DPRINTFN(4, "xfer %p pipe %p status %d",
   1602 	    xfer, xfer->ux_pipe, status, 0);
   1603 
   1604 	KASSERT(mutex_owned(&sc->sc_lock));
   1605 
   1606 	if (sc->sc_dying) {
   1607 		/* If we're dying, just do the software part. */
   1608 		DPRINTFN(4, "dying", 0, 0, 0, 0);
   1609 		xfer->ux_status = status;  /* make software ignore it */
   1610 		callout_stop(&xfer->ux_callout);
   1611 		usb_transfer_complete(xfer);
   1612 		return;
   1613 	}
   1614 
   1615 	/* XXX need more stuff */
   1616 	xfer->ux_status = status;
   1617 	callout_stop(&xfer->ux_callout);
   1618 	usb_transfer_complete(xfer);
   1619 
   1620 	KASSERT(mutex_owned(&sc->sc_lock));
   1621 }
   1622 
   1623 #if 1 /* XXX experimental */
   1624 /*
   1625  * Recover STALLed endpoint.
   1626  * xHCI 1.1 sect 4.10.2.1
   1627  * Issue RESET_EP to recover halt condition and SET_TR_DEQUEUE to remove
   1628  * all transfers on transfer ring.
   1629  * These are done in thread context asynchronously.
   1630  */
   1631 static void
   1632 xhci_clear_endpoint_stall_async_task(void *cookie)
   1633 {
   1634 	struct usbd_xfer * const xfer = cookie;
   1635 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   1636 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   1637 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   1638 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
   1639 
   1640 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1641 	DPRINTFN(4, "xfer %p slot %u dci %u", xfer, xs->xs_idx, dci, 0);
   1642 
   1643 	xhci_reset_endpoint(xfer->ux_pipe);
   1644 	xhci_set_dequeue(xfer->ux_pipe);
   1645 
   1646 	mutex_enter(&sc->sc_lock);
   1647 	tr->is_halted = false;
   1648 	usb_transfer_complete(xfer);
   1649 	mutex_exit(&sc->sc_lock);
   1650 	DPRINTFN(4, "ends", 0, 0, 0, 0);
   1651 }
   1652 
   1653 static usbd_status
   1654 xhci_clear_endpoint_stall_async(struct usbd_xfer *xfer)
   1655 {
   1656 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   1657 	struct xhci_pipe * const xp = (struct xhci_pipe *)xfer->ux_pipe;
   1658 
   1659 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1660 	DPRINTFN(4, "xfer %p", xfer, 0, 0, 0);
   1661 
   1662 	if (sc->sc_dying) {
   1663 		return USBD_IOERROR;
   1664 	}
   1665 
   1666 	usb_init_task(&xp->xp_async_task,
   1667 	    xhci_clear_endpoint_stall_async_task, xfer, USB_TASKQ_MPSAFE);
   1668 	usb_add_task(xfer->ux_pipe->up_dev, &xp->xp_async_task, USB_TASKQ_HC);
   1669 	DPRINTFN(4, "ends", 0, 0, 0, 0);
   1670 
   1671 	return USBD_NORMAL_COMPLETION;
   1672 }
   1673 
   1674 #endif /* XXX experimental */
   1675 
   1676 /*
   1677  * Notify roothub port status/change to uhub_intr.
   1678  */
   1679 static void
   1680 xhci_rhpsc(struct xhci_softc * const sc, u_int port)
   1681 {
   1682 	struct usbd_xfer * const xfer = sc->sc_intrxfer;
   1683 	uint8_t *p;
   1684 
   1685 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1686 	DPRINTFN(4, "xhci%d: port %u status change", device_unit(sc->sc_dev),
   1687 	    port, 0, 0);
   1688 
   1689 	if (xfer == NULL)
   1690 		return;
   1691 
   1692 	if (port > sc->sc_maxports)
   1693 		return;
   1694 
   1695 	p = xfer->ux_buf;
   1696 	memset(p, 0, xfer->ux_length);
   1697 	p[port/NBBY] |= 1 << (port%NBBY);
   1698 	xfer->ux_actlen = xfer->ux_length;
   1699 	xfer->ux_status = USBD_NORMAL_COMPLETION;
   1700 	usb_transfer_complete(xfer);
   1701 }
   1702 
   1703 /*
   1704  * Process events:
   1705  * + Transfer comeplete
   1706  * + Command complete
   1707  * + Roothub Port status/change
   1708  */
   1709 static void
   1710 xhci_handle_event(struct xhci_softc * const sc,
   1711     const struct xhci_trb * const trb)
   1712 {
   1713 	uint64_t trb_0;
   1714 	uint32_t trb_2, trb_3;
   1715 	uint8_t trberr;
   1716 
   1717 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1718 
   1719 	trb_0 = le64toh(trb->trb_0);
   1720 	trb_2 = le32toh(trb->trb_2);
   1721 	trb_3 = le32toh(trb->trb_3);
   1722 	trberr = XHCI_TRB_2_ERROR_GET(trb_2);
   1723 
   1724 	DPRINTFN(14, "event: %p 0x%016"PRIx64" 0x%08"PRIx32" 0x%08"PRIx32,
   1725 	    trb, trb_0, trb_2, trb_3);
   1726 
   1727 	switch (XHCI_TRB_3_TYPE_GET(trb_3)) {
   1728 	case XHCI_TRB_EVENT_TRANSFER: {
   1729 		u_int slot, dci;
   1730 		struct xhci_slot *xs;
   1731 		struct xhci_ring *xr;
   1732 		struct xhci_xfer *xx;
   1733 		struct usbd_xfer *xfer;
   1734 		usbd_status err;
   1735 
   1736 		slot = XHCI_TRB_3_SLOT_GET(trb_3);
   1737 		dci = XHCI_TRB_3_EP_GET(trb_3);
   1738 
   1739 		xs = &sc->sc_slots[slot];
   1740 		xr = &xs->xs_ep[dci].xe_tr;
   1741 		/* sanity check */
   1742 		if (xs->xs_idx == 0 || xs->xs_idx >= sc->sc_maxslots) {
   1743 			DPRINTFN(1, "invalid slot %u", xs->xs_idx, 0, 0, 0);
   1744 			break;
   1745 		}
   1746 
   1747 		if ((trb_3 & XHCI_TRB_3_ED_BIT) == 0) {
   1748 			bus_addr_t trbp = xhci_ring_trbp(xr, 0);
   1749 
   1750 			/* trb_0 range sanity check */
   1751 			if (trb_0 < trbp ||
   1752 			    (trb_0 - trbp) % sizeof(struct xhci_trb) != 0 ||
   1753 			    (trb_0 - trbp) / sizeof(struct xhci_trb) >=
   1754 			     xr->xr_ntrb) {
   1755 				DPRINTFN(1,
   1756 				    "invalid trb_0 0x%"PRIx64" trbp 0x%"PRIx64,
   1757 				    trb_0, trbp, 0, 0);
   1758 				break;
   1759 			}
   1760 			int idx = (trb_0 - trbp) / sizeof(struct xhci_trb);
   1761 			xx = xr->xr_cookies[idx];
   1762 		} else {
   1763 			xx = (void *)(uintptr_t)(trb_0 & ~0x3);
   1764 		}
   1765 		/* XXX this may not happen */
   1766 		if (xx == NULL) {
   1767 			DPRINTFN(1, "xfer done: xx is NULL", 0, 0, 0, 0);
   1768 			break;
   1769 		}
   1770 		xfer = &xx->xx_xfer;
   1771 		/* XXX this may happen when detaching */
   1772 		if (xfer == NULL) {
   1773 			DPRINTFN(1, "xfer done: xfer is NULL", 0, 0, 0, 0);
   1774 			break;
   1775 		}
   1776 		DPRINTFN(14, "xfer %p", xfer, 0, 0, 0);
   1777 		/* XXX I dunno why this happens */
   1778 		KASSERT(xfer->ux_pipe != NULL);
   1779 
   1780 		if (!xfer->ux_pipe->up_repeat &&
   1781 		    SIMPLEQ_EMPTY(&xfer->ux_pipe->up_queue)) {
   1782 			DPRINTFN(1, "xfer done: xfer not started", 0, 0, 0, 0);
   1783 			break;
   1784 		}
   1785 
   1786 		if ((trb_3 & XHCI_TRB_3_ED_BIT) != 0) {
   1787 			DPRINTFN(14, "transfer event data: "
   1788 			    "0x%016"PRIx64" 0x%08"PRIx32" %02x",
   1789 			    trb_0, XHCI_TRB_2_REM_GET(trb_2),
   1790 			    XHCI_TRB_2_ERROR_GET(trb_2), 0);
   1791 			if ((trb_0 & 0x3) == 0x3) {
   1792 				xfer->ux_actlen = XHCI_TRB_2_REM_GET(trb_2);
   1793 			}
   1794 		}
   1795 
   1796 		switch (trberr) {
   1797 		case XHCI_TRB_ERROR_SHORT_PKT:
   1798 		case XHCI_TRB_ERROR_SUCCESS:
   1799 			xfer->ux_actlen =
   1800 			    xfer->ux_length - XHCI_TRB_2_REM_GET(trb_2);
   1801 			err = USBD_NORMAL_COMPLETION;
   1802 			break;
   1803 		case XHCI_TRB_ERROR_STALL:
   1804 		case XHCI_TRB_ERROR_BABBLE:
   1805 			DPRINTFN(1, "evh: xfer done: ERR %u slot %u dci %u",
   1806 			    trberr, slot, dci, 0);
   1807 			xr->is_halted = true;
   1808 			err = USBD_STALLED;
   1809 #if 1 /* XXX experimental */
   1810 			/*
   1811 			 * Stalled endpoints can be recoverd by issuing
   1812 			 * command TRB TYPE_RESET_EP on xHCI instead of
   1813 			 * issuing request CLEAR_PORT_FEATURE UF_ENDPOINT_HALT
   1814 			 * on the endpoint. However, this function may be
   1815 			 * called from softint context (e.g. from umass),
   1816 			 * in that case driver gets KASSERT in cv_timedwait
   1817 			 * in xhci_do_command.
   1818 			 * To avoid this, this runs reset_endpoint and
   1819 			 * usb_transfer_complete in usb task thread
   1820 			 * asynchronously (and then umass issues clear
   1821 			 * UF_ENDPOINT_HALT).
   1822 			 */
   1823 			xfer->ux_status = err;
   1824 			xhci_clear_endpoint_stall_async(xfer);
   1825 			return;
   1826 #else
   1827 			break;
   1828 #endif
   1829 		case XHCI_TRB_ERROR_CMD_ABORTED:
   1830 		case XHCI_TRB_ERROR_STOPPED:
   1831 			err = USBD_CANCELLED;
   1832 			break;
   1833 		case XHCI_TRB_ERROR_NO_SLOTS:
   1834 			err = USBD_NO_ADDR;
   1835 			break;
   1836 		default:
   1837 			DPRINTFN(1, "evh: xfer done: ERR %u slot %u dci %u",
   1838 			    trberr, slot, dci, 0);
   1839 			err = USBD_IOERROR;
   1840 			break;
   1841 		}
   1842 		xfer->ux_status = err;
   1843 
   1844 		//mutex_enter(&sc->sc_lock); /* XXX ??? */
   1845 		if ((trb_3 & XHCI_TRB_3_ED_BIT) != 0) {
   1846 			if ((trb_0 & 0x3) == 0x0) {
   1847 				usb_transfer_complete(xfer);
   1848 			}
   1849 		} else {
   1850 			usb_transfer_complete(xfer);
   1851 		}
   1852 		//mutex_exit(&sc->sc_lock); /* XXX ??? */
   1853 
   1854 		}
   1855 		break;
   1856 	case XHCI_TRB_EVENT_CMD_COMPLETE:
   1857 		if (trb_0 == sc->sc_command_addr) {
   1858 			sc->sc_result_trb.trb_0 = trb_0;
   1859 			sc->sc_result_trb.trb_2 = trb_2;
   1860 			sc->sc_result_trb.trb_3 = trb_3;
   1861 			if (XHCI_TRB_2_ERROR_GET(trb_2) !=
   1862 			    XHCI_TRB_ERROR_SUCCESS) {
   1863 				DPRINTFN(1, "command completion "
   1864 				    "failure: 0x%016"PRIx64" 0x%08"PRIx32" "
   1865 				    "0x%08"PRIx32, trb_0, trb_2, trb_3, 0);
   1866 			}
   1867 			cv_signal(&sc->sc_command_cv);
   1868 		} else {
   1869 			DPRINTFN(1, "spurious event: %p 0x%016"PRIx64" "
   1870 			    "0x%08"PRIx32" 0x%08"PRIx32, trb, trb_0,
   1871 			    trb_2, trb_3);
   1872 		}
   1873 		break;
   1874 	case XHCI_TRB_EVENT_PORT_STS_CHANGE:
   1875 		xhci_rhpsc(sc, (uint32_t)((trb_0 >> 24) & 0xff));
   1876 		break;
   1877 	default:
   1878 		break;
   1879 	}
   1880 }
   1881 
   1882 static void
   1883 xhci_softintr(void *v)
   1884 {
   1885 	struct usbd_bus * const bus = v;
   1886 	struct xhci_softc * const sc = bus->ub_hcpriv;
   1887 	struct xhci_ring * const er = &sc->sc_er;
   1888 	struct xhci_trb *trb;
   1889 	int i, j, k;
   1890 
   1891 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1892 
   1893 	i = er->xr_ep;
   1894 	j = er->xr_cs;
   1895 
   1896 	DPRINTFN(16, "xr_ep %d xr_cs %d", i, j, 0, 0);
   1897 
   1898 	while (1) {
   1899 		usb_syncmem(&er->xr_dma, XHCI_TRB_SIZE * i, XHCI_TRB_SIZE,
   1900 		    BUS_DMASYNC_POSTREAD);
   1901 		trb = &er->xr_trb[i];
   1902 		k = (le32toh(trb->trb_3) & XHCI_TRB_3_CYCLE_BIT) ? 1 : 0;
   1903 
   1904 		if (j != k)
   1905 			break;
   1906 
   1907 		xhci_handle_event(sc, trb);
   1908 
   1909 		i++;
   1910 		if (i == XHCI_EVENT_RING_TRBS) {
   1911 			i = 0;
   1912 			j ^= 1;
   1913 		}
   1914 	}
   1915 
   1916 	er->xr_ep = i;
   1917 	er->xr_cs = j;
   1918 
   1919 	xhci_rt_write_8(sc, XHCI_ERDP(0), xhci_ring_trbp(er, er->xr_ep) |
   1920 	    XHCI_ERDP_LO_BUSY);
   1921 
   1922 	DPRINTFN(16, "ends", 0, 0, 0, 0);
   1923 
   1924 	return;
   1925 }
   1926 
   1927 static void
   1928 xhci_poll(struct usbd_bus *bus)
   1929 {
   1930 	struct xhci_softc * const sc = bus->ub_hcpriv;
   1931 
   1932 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1933 
   1934 	mutex_spin_enter(&sc->sc_intr_lock);
   1935 	xhci_intr1(sc);
   1936 	mutex_spin_exit(&sc->sc_intr_lock);
   1937 
   1938 	return;
   1939 }
   1940 
   1941 static struct usbd_xfer *
   1942 xhci_allocx(struct usbd_bus *bus)
   1943 {
   1944 	struct xhci_softc * const sc = bus->ub_hcpriv;
   1945 	struct usbd_xfer *xfer;
   1946 
   1947 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1948 
   1949 	xfer = pool_cache_get(sc->sc_xferpool, PR_NOWAIT);
   1950 	if (xfer != NULL) {
   1951 		memset(xfer, 0, sizeof(struct xhci_xfer));
   1952 #ifdef DIAGNOSTIC
   1953 		xfer->ux_state = XFER_BUSY;
   1954 #endif
   1955 	}
   1956 
   1957 	return xfer;
   1958 }
   1959 
   1960 static void
   1961 xhci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
   1962 {
   1963 	struct xhci_softc * const sc = bus->ub_hcpriv;
   1964 
   1965 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   1966 
   1967 #ifdef DIAGNOSTIC
   1968 	if (xfer->ux_state != XFER_BUSY) {
   1969 		DPRINTFN(0, "xfer=%p not busy, 0x%08x",
   1970 		    xfer, xfer->ux_state, 0, 0);
   1971 	}
   1972 	xfer->ux_state = XFER_FREE;
   1973 #endif
   1974 	pool_cache_put(sc->sc_xferpool, xfer);
   1975 }
   1976 
   1977 static void
   1978 xhci_get_lock(struct usbd_bus *bus, kmutex_t **lock)
   1979 {
   1980 	struct xhci_softc * const sc = bus->ub_hcpriv;
   1981 
   1982 	*lock = &sc->sc_lock;
   1983 }
   1984 
   1985 extern uint32_t usb_cookie_no;
   1986 
   1987 /*
   1988  * Called if uhub_explore find new device (via usbd_new_device).
   1989  * Allocate and construct dev structure of default endpoint (ep0).
   1990  *   Determine initial MaxPacketSize (mps) by speed.
   1991  *   Determine route string and roothub port for slot of dev.
   1992  * Allocate pipe of ep0.
   1993  * Enable and initialize slot and Set Address.
   1994  * Read device descriptor.
   1995  * Register this device.
   1996  */
   1997 static usbd_status
   1998 xhci_new_device(device_t parent, struct usbd_bus *bus, int depth,
   1999     int speed, int port, struct usbd_port *up)
   2000 {
   2001 	struct xhci_softc * const sc = bus->ub_hcpriv;
   2002 	struct usbd_device *dev;
   2003 	usbd_status err;
   2004 	usb_device_descriptor_t *dd;
   2005 	struct usbd_device *hub;
   2006 	struct usbd_device *adev;
   2007 	int rhport = 0;
   2008 	struct xhci_slot *xs;
   2009 	uint32_t *cp;
   2010 	uint32_t route = 0;
   2011 	uint8_t slot = 0;
   2012 	uint8_t addr;
   2013 
   2014 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2015 	DPRINTFN(4, "port=%d depth=%d speed=%d upport %d",
   2016 		 port, depth, speed, up->up_portno);
   2017 
   2018 	dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
   2019 	if (dev == NULL)
   2020 		return USBD_NOMEM;
   2021 
   2022 	dev->ud_bus = bus;
   2023 
   2024 	/* Set up default endpoint handle. */
   2025 	dev->ud_ep0.ue_edesc = &dev->ud_ep0desc;
   2026 
   2027 	/* Set up default endpoint descriptor. */
   2028 	dev->ud_ep0desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
   2029 	dev->ud_ep0desc.bDescriptorType = UDESC_ENDPOINT;
   2030 	dev->ud_ep0desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
   2031 	dev->ud_ep0desc.bmAttributes = UE_CONTROL;
   2032 	/* 4.3,  4.8.2.1 */
   2033 	if (USB_IS_SS(speed)) {
   2034 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_3_MAX_CTRL_PACKET);
   2035 	} else
   2036 	switch (speed) {
   2037 	case USB_SPEED_FULL:
   2038 		/* XXX using 64 as initial mps of ep0 in FS */
   2039 	case USB_SPEED_HIGH:
   2040 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_2_MAX_CTRL_PACKET);
   2041 		break;
   2042 	case USB_SPEED_LOW:
   2043 	default:
   2044 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_MAX_IPACKET);
   2045 		break;
   2046 	}
   2047 	dev->ud_ep0desc.bInterval = 0;
   2048 
   2049 	/* doesn't matter, just don't let it uninitialized */
   2050 	dev->ud_ep0.ue_toggle = 0;
   2051 
   2052 	DPRINTFN(4, "up %p portno %d", up, up->up_portno, 0, 0);
   2053 
   2054 	dev->ud_quirks = &usbd_no_quirk;
   2055 	dev->ud_addr = 0;
   2056 	dev->ud_ddesc.bMaxPacketSize = 0;
   2057 	dev->ud_depth = depth;
   2058 	dev->ud_powersrc = up;
   2059 	dev->ud_myhub = up->up_parent;
   2060 
   2061 	up->up_dev = dev;
   2062 
   2063 	/* Locate root hub port */
   2064 	for (hub = dev; hub != NULL; hub = hub->ud_myhub) {
   2065 		uint32_t dep;
   2066 
   2067 		DPRINTFN(4, "hub %p depth %d upport %p upportno %d",
   2068 		    hub, hub->ud_depth, hub->ud_powersrc,
   2069 		    hub->ud_powersrc ? hub->ud_powersrc->up_portno : -1);
   2070 
   2071 		if (hub->ud_powersrc == NULL)
   2072 			break;
   2073 		dep = hub->ud_depth;
   2074 		if (dep == 0)
   2075 			break;
   2076 		rhport = hub->ud_powersrc->up_portno;
   2077 		if (dep > USB_HUB_MAX_DEPTH)
   2078 			continue;
   2079 
   2080 		route |=
   2081 		    (rhport > UHD_SS_NPORTS_MAX ? UHD_SS_NPORTS_MAX : rhport)
   2082 		    << ((dep - 1) * 4);
   2083 	}
   2084 	route = route >> 4;
   2085 	DPRINTFN(4, "rhport %d Route %05x hub %p", rhport, route, hub, 0);
   2086 
   2087 	/* Locate port on upstream high speed hub */
   2088 	for (adev = dev, hub = up->up_parent;
   2089 	     hub != NULL && hub->ud_speed != USB_SPEED_HIGH;
   2090 	     adev = hub, hub = hub->ud_myhub)
   2091 		;
   2092 	if (hub) {
   2093 		int p;
   2094 		for (p = 0; p < hub->ud_hub->uh_hubdesc.bNbrPorts; p++) {
   2095 			if (hub->ud_hub->uh_ports[p].up_dev == adev) {
   2096 				dev->ud_myhsport = &hub->ud_hub->uh_ports[p];
   2097 				goto found;
   2098 			}
   2099 		}
   2100 		panic("xhci_new_device: cannot find HS port");
   2101 	found:
   2102 		DPRINTFN(4, "high speed port %d", p, 0, 0, 0);
   2103 	} else {
   2104 		dev->ud_myhsport = NULL;
   2105 	}
   2106 
   2107 	dev->ud_speed = speed;
   2108 	dev->ud_langid = USBD_NOLANG;
   2109 	dev->ud_cookie.cookie = ++usb_cookie_no;
   2110 
   2111 	/* Establish the default pipe. */
   2112 	err = usbd_setup_pipe(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   2113 	    &dev->ud_pipe0);
   2114 	if (err) {
   2115 		goto bad;
   2116 	}
   2117 
   2118 	dd = &dev->ud_ddesc;
   2119 
   2120 	if ((depth == 0) && (port == 0)) {
   2121 		KASSERT(bus->ub_devices[dev->ud_addr] == NULL);
   2122 		bus->ub_devices[dev->ud_addr] = dev;
   2123 		err = usbd_get_initial_ddesc(dev, dd);
   2124 		if (err)
   2125 			goto bad;
   2126 		err = usbd_reload_device_desc(dev);
   2127 		if (err)
   2128 			goto bad;
   2129 	} else {
   2130 		err = xhci_enable_slot(sc, &slot);
   2131 		if (err)
   2132 			goto bad;
   2133 		xs = &sc->sc_slots[slot];
   2134 		dev->ud_hcpriv = xs;
   2135 		err = xhci_init_slot(dev, slot, route, rhport);
   2136 		if (err) {
   2137 			dev->ud_hcpriv = NULL;
   2138 			/*
   2139 			 * We have to disable_slot here because
   2140 			 * xs->xs_idx == 0 when xhci_init_slot fails,
   2141 			 * in that case usbd_remove_dev won't work.
   2142 			 */
   2143 			mutex_enter(&sc->sc_lock);
   2144 			xhci_disable_slot(sc, slot);
   2145 			mutex_exit(&sc->sc_lock);
   2146 			goto bad;
   2147 		}
   2148 
   2149 		/* Allow device time to set new address */
   2150 		usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   2151 		cp = xhci_slot_get_dcv(sc, xs, XHCI_DCI_SLOT);
   2152 		//hexdump("slot context", cp, sc->sc_ctxsz);
   2153 		addr = XHCI_SCTX_3_DEV_ADDR_GET(cp[3]);
   2154 		DPRINTFN(4, "device address %u", addr, 0, 0, 0);
   2155 		/* XXX ensure we know when the hardware does something
   2156 		   we can't yet cope with */
   2157 		KASSERT(addr >= 1 && addr <= 127);
   2158 		dev->ud_addr = addr;
   2159 		/* XXX dev->ud_addr not necessarily unique on bus */
   2160 		KASSERT(bus->ub_devices[dev->ud_addr] == NULL);
   2161 		bus->ub_devices[dev->ud_addr] = dev;
   2162 
   2163 		err = usbd_get_initial_ddesc(dev, dd);
   2164 		if (err)
   2165 			goto bad;
   2166 		/* 4.8.2.1 */
   2167 		if (USB_IS_SS(speed)) {
   2168 			if (dd->bMaxPacketSize != 9) {
   2169 				printf("%s: invalid mps 2^%u for SS ep0,"
   2170 				    " using 512\n",
   2171 				    device_xname(sc->sc_dev),
   2172 				    dd->bMaxPacketSize);
   2173 				dd->bMaxPacketSize = 9;
   2174 			}
   2175 			USETW(dev->ud_ep0desc.wMaxPacketSize,
   2176 			    (1 << dd->bMaxPacketSize));
   2177 		} else
   2178 	 		USETW(dev->ud_ep0desc.wMaxPacketSize,
   2179 			    dd->bMaxPacketSize);
   2180 		DPRINTFN(4, "bMaxPacketSize %u", dd->bMaxPacketSize, 0, 0, 0);
   2181 		xhci_update_ep0_mps(sc, xs,
   2182 		    UGETW(dev->ud_ep0desc.wMaxPacketSize));
   2183 		err = usbd_reload_device_desc(dev);
   2184 		if (err)
   2185 			goto bad;
   2186 
   2187 #if 0
   2188 		/* Re-establish the default pipe with the new MPS. */
   2189 		/* In xhci this is done by xhci_update_ep0_mps. */
   2190 		usbd_kill_pipe(dev->ud_pipe0);
   2191 		err = usbd_setup_pipe(dev, 0, &dev->ud_ep0,
   2192 		    USBD_DEFAULT_INTERVAL, &dev->ud_pipe0);
   2193 #endif
   2194 	}
   2195 
   2196 	DPRINTFN(1, "adding unit addr=%d, rev=%02x,",
   2197 		dev->ud_addr, UGETW(dd->bcdUSB), 0, 0);
   2198 	DPRINTFN(1, " class=%d, subclass=%d, protocol=%d,",
   2199 		dd->bDeviceClass, dd->bDeviceSubClass,
   2200 		dd->bDeviceProtocol, 0);
   2201 	DPRINTFN(1, " mps=%d, len=%d, noconf=%d, speed=%d",
   2202 		dd->bMaxPacketSize, dd->bLength, dd->bNumConfigurations,
   2203 		dev->ud_speed);
   2204 
   2205 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   2206 
   2207 	if ((depth == 0) && (port == 0)) {
   2208 		usbd_attach_roothub(parent, dev);
   2209 		DPRINTFN(1, "root_hub %p", bus->ub_roothub, 0, 0, 0);
   2210 		return USBD_NORMAL_COMPLETION;
   2211 	}
   2212 
   2213 
   2214 	err = usbd_probe_and_attach(parent, dev, port, dev->ud_addr);
   2215  bad:
   2216 	if (err != USBD_NORMAL_COMPLETION) {
   2217 		usbd_remove_device(dev, up);
   2218 	}
   2219 
   2220 	return err;
   2221 }
   2222 
   2223 static usbd_status
   2224 xhci_ring_init(struct xhci_softc * const sc, struct xhci_ring * const xr,
   2225     size_t ntrb, size_t align)
   2226 {
   2227 	usbd_status err;
   2228 	size_t size = ntrb * XHCI_TRB_SIZE;
   2229 
   2230 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2231 
   2232 	err = usb_allocmem(&sc->sc_bus, size, align, &xr->xr_dma);
   2233 	if (err)
   2234 		return err;
   2235 	mutex_init(&xr->xr_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
   2236 	xr->xr_cookies = kmem_zalloc(sizeof(*xr->xr_cookies) * ntrb, KM_SLEEP);
   2237 	xr->xr_trb = xhci_ring_trbv(xr, 0);
   2238 	xr->xr_ntrb = ntrb;
   2239 	xr->xr_ep = 0;
   2240 	xr->xr_cs = 1;
   2241 	memset(xr->xr_trb, 0, size);
   2242 	usb_syncmem(&xr->xr_dma, 0, size, BUS_DMASYNC_PREWRITE);
   2243 	xr->is_halted = false;
   2244 
   2245 	return USBD_NORMAL_COMPLETION;
   2246 }
   2247 
   2248 static void
   2249 xhci_ring_free(struct xhci_softc * const sc, struct xhci_ring * const xr)
   2250 {
   2251 	usb_freemem(&sc->sc_bus, &xr->xr_dma);
   2252 	mutex_destroy(&xr->xr_lock);
   2253 	kmem_free(xr->xr_cookies, sizeof(*xr->xr_cookies) * xr->xr_ntrb);
   2254 }
   2255 
   2256 static void
   2257 xhci_ring_put(struct xhci_softc * const sc, struct xhci_ring * const xr,
   2258     void *cookie, struct xhci_trb * const trbs, size_t ntrbs)
   2259 {
   2260 	size_t i;
   2261 	u_int ri;
   2262 	u_int cs;
   2263 	uint64_t parameter;
   2264 	uint32_t status;
   2265 	uint32_t control;
   2266 
   2267 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2268 
   2269 	for (i = 0; i < ntrbs; i++) {
   2270 		DPRINTFN(12, "xr %p trbs %p num %zu", xr, trbs, i, 0);
   2271 		DPRINTFN(12, " %016"PRIx64" %08"PRIx32" %08"PRIx32,
   2272 		    trbs[i].trb_0, trbs[i].trb_2, trbs[i].trb_3, 0);
   2273 		KASSERT(XHCI_TRB_3_TYPE_GET(trbs[i].trb_3) !=
   2274 		    XHCI_TRB_TYPE_LINK);
   2275 	}
   2276 
   2277 	DPRINTFN(12, "%p xr_ep 0x%x xr_cs %u", xr, xr->xr_ep, xr->xr_cs, 0);
   2278 
   2279 	ri = xr->xr_ep;
   2280 	cs = xr->xr_cs;
   2281 
   2282 	/*
   2283 	 * Although the xhci hardware can do scatter/gather dma from
   2284 	 * arbitrary sized buffers, there is a non-obvious restriction
   2285 	 * that a LINK trb is only allowed at the end of a burst of
   2286 	 * transfers - which might be 16kB.
   2287 	 * Arbitrary aligned LINK trb definitely fail on Ivy bridge.
   2288 	 * The simple solution is not to allow a LINK trb in the middle
   2289 	 * of anything - as here.
   2290 	 * XXX: (dsl) There are xhci controllers out there (eg some made by
   2291 	 * ASMedia) that seem to lock up if they process a LINK trb but
   2292 	 * cannot process the linked-to trb yet.
   2293 	 * The code should write the 'cycle' bit on the link trb AFTER
   2294 	 * adding the other trb.
   2295 	 */
   2296 	if (ri + ntrbs >= (xr->xr_ntrb - 1)) {
   2297 		parameter = xhci_ring_trbp(xr, 0);
   2298 		status = 0;
   2299 		control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
   2300 		    XHCI_TRB_3_TC_BIT | (cs ? XHCI_TRB_3_CYCLE_BIT : 0);
   2301 		xhci_trb_put(&xr->xr_trb[ri], htole64(parameter),
   2302 		    htole32(status), htole32(control));
   2303 		usb_syncmem(&xr->xr_dma, XHCI_TRB_SIZE * ri, XHCI_TRB_SIZE * 1,
   2304 		    BUS_DMASYNC_PREWRITE);
   2305 		xr->xr_cookies[ri] = NULL;
   2306 		xr->xr_ep = 0;
   2307 		xr->xr_cs ^= 1;
   2308 		ri = xr->xr_ep;
   2309 		cs = xr->xr_cs;
   2310 	}
   2311 
   2312 	ri++;
   2313 
   2314 	/* Write any subsequent TRB first */
   2315 	for (i = 1; i < ntrbs; i++) {
   2316 		parameter = trbs[i].trb_0;
   2317 		status = trbs[i].trb_2;
   2318 		control = trbs[i].trb_3;
   2319 
   2320 		if (cs) {
   2321 			control |= XHCI_TRB_3_CYCLE_BIT;
   2322 		} else {
   2323 			control &= ~XHCI_TRB_3_CYCLE_BIT;
   2324 		}
   2325 
   2326 		xhci_trb_put(&xr->xr_trb[ri], htole64(parameter),
   2327 		    htole32(status), htole32(control));
   2328 		usb_syncmem(&xr->xr_dma, XHCI_TRB_SIZE * ri, XHCI_TRB_SIZE * 1,
   2329 		    BUS_DMASYNC_PREWRITE);
   2330 		xr->xr_cookies[ri] = cookie;
   2331 		ri++;
   2332 	}
   2333 
   2334 	/* Write the first TRB last */
   2335 	i = 0;
   2336 	parameter = trbs[i].trb_0;
   2337 	status = trbs[i].trb_2;
   2338 	control = trbs[i].trb_3;
   2339 
   2340 	if (xr->xr_cs) {
   2341 		control |= XHCI_TRB_3_CYCLE_BIT;
   2342 	} else {
   2343 		control &= ~XHCI_TRB_3_CYCLE_BIT;
   2344 	}
   2345 
   2346 	xhci_trb_put(&xr->xr_trb[xr->xr_ep], htole64(parameter),
   2347 	    htole32(status), htole32(control));
   2348 	usb_syncmem(&xr->xr_dma, XHCI_TRB_SIZE * ri, XHCI_TRB_SIZE * 1,
   2349 	    BUS_DMASYNC_PREWRITE);
   2350 	xr->xr_cookies[xr->xr_ep] = cookie;
   2351 
   2352 	xr->xr_ep = ri;
   2353 	xr->xr_cs = cs;
   2354 
   2355 	DPRINTFN(12, "%p xr_ep 0x%x xr_cs %u", xr, xr->xr_ep, xr->xr_cs, 0);
   2356 }
   2357 
   2358 /*
   2359  * Put a command on command ring, ring bell, set timer, and cv_timedwait.
   2360  * Command completion is notified by cv_signal from xhci_handle_event
   2361  * (called from interrupt from xHCI), or timed-out.
   2362  * Command validation is performed in xhci_handle_event by checking if
   2363  * trb_0 in CMD_COMPLETE TRB and sc->sc_command_addr are identical.
   2364  */
   2365 static usbd_status
   2366 xhci_do_command1(struct xhci_softc * const sc, struct xhci_trb * const trb,
   2367     int timeout, int locked)
   2368 {
   2369 	struct xhci_ring * const cr = &sc->sc_cr;
   2370 	usbd_status err;
   2371 
   2372 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2373 	DPRINTFN(12, "input: 0x%016"PRIx64" 0x%08"PRIx32" 0x%08"PRIx32,
   2374 	    trb->trb_0, trb->trb_2, trb->trb_3, 0);
   2375 
   2376 	KASSERTMSG(!cpu_intr_p() && !cpu_softintr_p(), "called from intr ctx");
   2377 
   2378 	if (!locked)
   2379 		mutex_enter(&sc->sc_lock);
   2380 
   2381 	/* XXX KASSERT may fire when cv_timedwait unlocks sc_lock */
   2382 	KASSERT(sc->sc_command_addr == 0);
   2383 	sc->sc_command_addr = xhci_ring_trbp(cr, cr->xr_ep);
   2384 
   2385 	mutex_enter(&cr->xr_lock);
   2386 	xhci_ring_put(sc, cr, NULL, trb, 1);
   2387 	mutex_exit(&cr->xr_lock);
   2388 
   2389 	xhci_db_write_4(sc, XHCI_DOORBELL(0), 0);
   2390 
   2391 	if (cv_timedwait(&sc->sc_command_cv, &sc->sc_lock,
   2392 	    MAX(1, mstohz(timeout))) == EWOULDBLOCK) {
   2393 		err = USBD_TIMEOUT;
   2394 		goto timedout;
   2395 	}
   2396 
   2397 	trb->trb_0 = sc->sc_result_trb.trb_0;
   2398 	trb->trb_2 = sc->sc_result_trb.trb_2;
   2399 	trb->trb_3 = sc->sc_result_trb.trb_3;
   2400 
   2401 	DPRINTFN(12, "output: 0x%016"PRIx64" 0x%08"PRIx32" 0x%08"PRIx32"",
   2402 	    trb->trb_0, trb->trb_2, trb->trb_3, 0);
   2403 
   2404 	switch (XHCI_TRB_2_ERROR_GET(trb->trb_2)) {
   2405 	case XHCI_TRB_ERROR_SUCCESS:
   2406 		err = USBD_NORMAL_COMPLETION;
   2407 		break;
   2408 	default:
   2409 	case 192 ... 223:
   2410 		err = USBD_IOERROR;
   2411 		break;
   2412 	case 224 ... 255:
   2413 		err = USBD_NORMAL_COMPLETION;
   2414 		break;
   2415 	}
   2416 
   2417 timedout:
   2418 	sc->sc_command_addr = 0;
   2419 	if (!locked)
   2420 		mutex_exit(&sc->sc_lock);
   2421 	return err;
   2422 }
   2423 
   2424 static usbd_status
   2425 xhci_do_command(struct xhci_softc * const sc, struct xhci_trb * const trb,
   2426     int timeout)
   2427 {
   2428 	return xhci_do_command1(sc, trb, timeout, 0);
   2429 }
   2430 
   2431 /*
   2432  * This allows xhci_do_command with already sc_lock held.
   2433  * This is needed as USB stack calls close methods with sc_lock_held.
   2434  * (see usbdivar.h)
   2435  */
   2436 static usbd_status
   2437 xhci_do_command_locked(struct xhci_softc * const sc,
   2438     struct xhci_trb * const trb, int timeout)
   2439 {
   2440 	return xhci_do_command1(sc, trb, timeout, 1);
   2441 }
   2442 
   2443 static usbd_status
   2444 xhci_enable_slot(struct xhci_softc * const sc, uint8_t * const slotp)
   2445 {
   2446 	struct xhci_trb trb;
   2447 	usbd_status err;
   2448 
   2449 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2450 
   2451 	trb.trb_0 = 0;
   2452 	trb.trb_2 = 0;
   2453 	trb.trb_3 = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT);
   2454 
   2455 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   2456 	if (err != USBD_NORMAL_COMPLETION) {
   2457 		return err;
   2458 	}
   2459 
   2460 	*slotp = XHCI_TRB_3_SLOT_GET(trb.trb_3);
   2461 
   2462 	return err;
   2463 }
   2464 
   2465 /*
   2466  * Deallocate DMA buffer and ring buffer, and disable_slot.
   2467  * Should be called with sc_lock held.
   2468  */
   2469 static usbd_status
   2470 xhci_disable_slot(struct xhci_softc * const sc, uint8_t slot)
   2471 {
   2472 	struct xhci_trb trb;
   2473 	struct xhci_slot *xs;
   2474 
   2475 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2476 
   2477 	if (sc->sc_dying)
   2478 		return USBD_IOERROR;
   2479 
   2480 	xs = &sc->sc_slots[slot];
   2481 	if (xs->xs_idx != 0) {
   2482 		for (int i = XHCI_DCI_SLOT + 1; i < 32; i++) {
   2483 			xhci_ring_free(sc, &xs->xs_ep[i].xe_tr);
   2484 			memset(&xs->xs_ep[i], 0, sizeof(xs->xs_ep[i]));
   2485 		}
   2486 		usb_freemem(&sc->sc_bus, &xs->xs_ic_dma);
   2487 		usb_freemem(&sc->sc_bus, &xs->xs_dc_dma);
   2488 	}
   2489 
   2490 	trb.trb_0 = 0;
   2491 	trb.trb_2 = 0;
   2492 	trb.trb_3 = htole32(
   2493 		XHCI_TRB_3_SLOT_SET(slot) |
   2494 		XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT));
   2495 
   2496 	return xhci_do_command_locked(sc, &trb, USBD_DEFAULT_TIMEOUT);
   2497 }
   2498 
   2499 /*
   2500  * Change slot state.
   2501  * bsr=0: ENABLED -> ADDRESSED
   2502  * bsr=1: ENABLED -> DEFAULT
   2503  * see xHCI 1.1  4.5.3, 3.3.4
   2504  */
   2505 static usbd_status
   2506 xhci_address_device(struct xhci_softc * const sc,
   2507     uint64_t icp, uint8_t slot_id, bool bsr)
   2508 {
   2509 	struct xhci_trb trb;
   2510 	usbd_status err;
   2511 
   2512 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2513 
   2514 	trb.trb_0 = icp;
   2515 	trb.trb_2 = 0;
   2516 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(slot_id) |
   2517 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
   2518 	    (bsr ? XHCI_TRB_3_BSR_BIT : 0);
   2519 
   2520 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   2521 	return err;
   2522 }
   2523 
   2524 static usbd_status
   2525 xhci_update_ep0_mps(struct xhci_softc * const sc,
   2526     struct xhci_slot * const xs, u_int mps)
   2527 {
   2528 	struct xhci_trb trb;
   2529 	usbd_status err;
   2530 	uint32_t * cp;
   2531 
   2532 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2533 	DPRINTFN(4, "slot %u mps %u", xs->xs_idx, mps, 0, 0);
   2534 
   2535 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
   2536 	cp[0] = htole32(0);
   2537 	cp[1] = htole32(XHCI_INCTX_1_ADD_MASK(XHCI_DCI_EP_CONTROL));
   2538 
   2539 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_EP_CONTROL));
   2540 	cp[1] = htole32(XHCI_EPCTX_1_MAXP_SIZE_SET(mps));
   2541 
   2542 	/* sync input contexts before they are read from memory */
   2543 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
   2544 	hexdump("input context", xhci_slot_get_icv(sc, xs, 0),
   2545 	    sc->sc_ctxsz * 4);
   2546 
   2547 	trb.trb_0 = xhci_slot_get_icp(sc, xs, 0);
   2548 	trb.trb_2 = 0;
   2549 	trb.trb_3 = XHCI_TRB_3_SLOT_SET(xs->xs_idx) |
   2550 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX);
   2551 
   2552 	err = xhci_do_command(sc, &trb, USBD_DEFAULT_TIMEOUT);
   2553 	KASSERT(err == USBD_NORMAL_COMPLETION); /* XXX */
   2554 	return err;
   2555 }
   2556 
   2557 static void
   2558 xhci_set_dcba(struct xhci_softc * const sc, uint64_t dcba, int si)
   2559 {
   2560 	uint64_t * const dcbaa = KERNADDR(&sc->sc_dcbaa_dma, 0);
   2561 
   2562 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2563 	DPRINTFN(4, "dcbaa %p dc %016"PRIx64" slot %d",
   2564 	    &dcbaa[si], dcba, si, 0);
   2565 
   2566 	dcbaa[si] = htole64(dcba);
   2567 	usb_syncmem(&sc->sc_dcbaa_dma, si * sizeof(uint64_t), sizeof(uint64_t),
   2568 	    BUS_DMASYNC_PREWRITE);
   2569 }
   2570 
   2571 /*
   2572  * Allocate DMA buffer and ring buffer for specified slot
   2573  * and set Device Context Base Address
   2574  * and issue Set Address device command.
   2575  */
   2576 static usbd_status
   2577 xhci_init_slot(struct usbd_device *dev, uint32_t slot, int route, int rhport)
   2578 {
   2579 	struct xhci_softc * const sc = dev->ud_bus->ub_hcpriv;
   2580 	struct xhci_slot *xs;
   2581 	usbd_status err;
   2582 	u_int dci;
   2583 	uint32_t *cp;
   2584 	uint32_t mps = UGETW(dev->ud_ep0desc.wMaxPacketSize);
   2585 
   2586 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2587 	DPRINTFN(4, "slot %u speed %d rhport %d route %05x",
   2588 	    slot, dev->ud_speed, route, rhport);
   2589 
   2590 	xs = &sc->sc_slots[slot];
   2591 
   2592 	/* allocate contexts */
   2593 	err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz, sc->sc_pgsz,
   2594 	    &xs->xs_dc_dma);
   2595 	if (err)
   2596 		return err;
   2597 	memset(KERNADDR(&xs->xs_dc_dma, 0), 0, sc->sc_pgsz);
   2598 
   2599 	err = usb_allocmem(&sc->sc_bus, sc->sc_pgsz, sc->sc_pgsz,
   2600 	    &xs->xs_ic_dma);
   2601 	if (err)
   2602 		goto bad1;
   2603 	memset(KERNADDR(&xs->xs_ic_dma, 0), 0, sc->sc_pgsz);
   2604 
   2605 	for (dci = 0; dci < 32; dci++) {
   2606 		//CTASSERT(sizeof(xs->xs_ep[dci]) == sizeof(struct xhci_endpoint));
   2607 		memset(&xs->xs_ep[dci], 0, sizeof(xs->xs_ep[dci]));
   2608 		if (dci == XHCI_DCI_SLOT)
   2609 			continue;
   2610 		err = xhci_ring_init(sc, &xs->xs_ep[dci].xe_tr,
   2611 		    XHCI_TRANSFER_RING_TRBS, XHCI_TRB_ALIGN);
   2612 		if (err) {
   2613 			DPRINTFN(0, "ring init failure", 0, 0, 0, 0);
   2614 			goto bad2;
   2615 		}
   2616 	}
   2617 
   2618 	/* set up initial input control context */
   2619 	cp = xhci_slot_get_icv(sc, xs, XHCI_ICI_INPUT_CONTROL);
   2620 	cp[0] = htole32(0);
   2621 	cp[1] = htole32(XHCI_INCTX_1_ADD_MASK(XHCI_DCI_EP_CONTROL)|
   2622 	    XHCI_INCTX_1_ADD_MASK(XHCI_DCI_SLOT));
   2623 
   2624 	/* set up input slot context */
   2625 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_SLOT));
   2626 	xhci_setup_sctx(dev, cp);
   2627 	cp[0] |= htole32(XHCI_SCTX_0_CTX_NUM_SET(1));
   2628 	cp[0] |= htole32(XHCI_SCTX_0_ROUTE_SET(route));
   2629 	cp[1] |= htole32(XHCI_SCTX_1_RH_PORT_SET(rhport));
   2630 
   2631 	/* set up input EP0 context */
   2632 	cp = xhci_slot_get_icv(sc, xs, xhci_dci_to_ici(XHCI_DCI_EP_CONTROL));
   2633 	cp[0] = htole32(0);
   2634 	cp[1] = htole32(
   2635 		XHCI_EPCTX_1_MAXP_SIZE_SET(mps) |
   2636 		XHCI_EPCTX_1_EPTYPE_SET(4) |
   2637 		XHCI_EPCTX_1_CERR_SET(3)
   2638 		);
   2639 	/* can't use xhci_ep_get_dci() yet? */
   2640 	*(uint64_t *)(&cp[2]) = htole64(
   2641 	    xhci_ring_trbp(&xs->xs_ep[XHCI_DCI_EP_CONTROL].xe_tr, 0) |
   2642 	    XHCI_EPCTX_2_DCS_SET(1));
   2643 	cp[4] = htole32(
   2644 		XHCI_EPCTX_4_AVG_TRB_LEN_SET(8)
   2645 		);
   2646 
   2647 	/* sync input contexts before they are read from memory */
   2648 	usb_syncmem(&xs->xs_ic_dma, 0, sc->sc_pgsz, BUS_DMASYNC_PREWRITE);
   2649 	hexdump("input context", xhci_slot_get_icv(sc, xs, 0),
   2650 	    sc->sc_ctxsz * 3);
   2651 
   2652 	xhci_set_dcba(sc, DMAADDR(&xs->xs_dc_dma, 0), slot);
   2653 
   2654 	err = xhci_address_device(sc, xhci_slot_get_icp(sc, xs, 0), slot,
   2655 	    false);
   2656 
   2657 	usb_syncmem(&xs->xs_dc_dma, 0, sc->sc_pgsz, BUS_DMASYNC_POSTREAD);
   2658 	hexdump("output context", xhci_slot_get_dcv(sc, xs, 0),
   2659 	    sc->sc_ctxsz * 2);
   2660 
   2661  bad2:
   2662 	if (err == USBD_NORMAL_COMPLETION) {
   2663 		xs->xs_idx = slot;
   2664 	} else {
   2665 		for (int i = 1; i < dci; i++) {
   2666 			xhci_ring_free(sc, &xs->xs_ep[i].xe_tr);
   2667 			memset(&xs->xs_ep[i], 0, sizeof(xs->xs_ep[i]));
   2668 		}
   2669 		usb_freemem(&sc->sc_bus, &xs->xs_ic_dma);
   2670  bad1:
   2671 		usb_freemem(&sc->sc_bus, &xs->xs_dc_dma);
   2672 		xs->xs_idx = 0;
   2673 	}
   2674 
   2675 	return err;
   2676 }
   2677 
   2678 /* ----- */
   2679 
   2680 static void
   2681 xhci_noop(struct usbd_pipe *pipe)
   2682 {
   2683 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2684 }
   2685 
   2686 /*
   2687  * Process root hub request.
   2688  */
   2689 static int
   2690 xhci_roothub_ctrl(struct usbd_bus *bus, usb_device_request_t *req,
   2691     void *buf, int buflen)
   2692 {
   2693 	struct xhci_softc * const sc = bus->ub_hcpriv;
   2694 	usb_port_status_t ps;
   2695 	int l, totlen = 0;
   2696 	uint16_t len, value, index;
   2697 	int port, i;
   2698 	uint32_t v;
   2699 
   2700 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2701 
   2702 	if (sc->sc_dying)
   2703 		return -1;
   2704 
   2705 	len = UGETW(req->wLength);
   2706 	value = UGETW(req->wValue);
   2707 	index = UGETW(req->wIndex);
   2708 
   2709 	DPRINTFN(12, "rhreq: %04x %04x %04x %04x",
   2710 	    req->bmRequestType | (req->bRequest << 8), value, index, len);
   2711 
   2712 #define C(x,y) ((x) | ((y) << 8))
   2713 	switch (C(req->bRequest, req->bmRequestType)) {
   2714 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
   2715 		DPRINTFN(8, "getdesc: wValue=0x%04x", value, 0, 0, 0);
   2716 		if (len == 0)
   2717 			break;
   2718 		switch (value) {
   2719 #define sd ((usb_string_descriptor_t *)buf)
   2720 		case C(2, UDESC_STRING):
   2721 			/* Product */
   2722 			totlen = usb_makestrdesc(sd, len, "xHCI Root Hub");
   2723 			break;
   2724 #undef sd
   2725 		default:
   2726 			/* default from usbroothub */
   2727 			return buflen;
   2728 		}
   2729 		break;
   2730 
   2731 	/* Hub requests */
   2732 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
   2733 		break;
   2734 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
   2735 		DPRINTFN(4, "UR_CLEAR_PORT_FEATURE port=%d feature=%d",
   2736 			     index, value, 0, 0);
   2737 		if (index < 1 || index > sc->sc_maxports) {
   2738 			return -1;
   2739 		}
   2740 		port = XHCI_PORTSC(index);
   2741 		v = xhci_op_read_4(sc, port);
   2742 		DPRINTFN(4, "portsc=0x%08x", v, 0, 0, 0);
   2743 		v &= ~XHCI_PS_CLEAR;
   2744 		switch (value) {
   2745 		case UHF_PORT_ENABLE:
   2746 			xhci_op_write_4(sc, port, v &~ XHCI_PS_PED);
   2747 			break;
   2748 		case UHF_PORT_SUSPEND:
   2749 			return -1;
   2750 		case UHF_PORT_POWER:
   2751 			break;
   2752 		case UHF_PORT_TEST:
   2753 		case UHF_PORT_INDICATOR:
   2754 			return -1;
   2755 		case UHF_C_PORT_CONNECTION:
   2756 			xhci_op_write_4(sc, port, v | XHCI_PS_CSC);
   2757 			break;
   2758 		case UHF_C_PORT_ENABLE:
   2759 		case UHF_C_PORT_SUSPEND:
   2760 		case UHF_C_PORT_OVER_CURRENT:
   2761 			return -1;
   2762 		case UHF_C_BH_PORT_RESET:
   2763 			xhci_op_write_4(sc, port, v | XHCI_PS_WRC);
   2764 			break;
   2765 		case UHF_C_PORT_RESET:
   2766 			xhci_op_write_4(sc, port, v | XHCI_PS_PRC);
   2767 			break;
   2768 		case UHF_C_PORT_LINK_STATE:
   2769 			xhci_op_write_4(sc, port, v | XHCI_PS_PLC);
   2770 			break;
   2771 		case UHF_C_PORT_CONFIG_ERROR:
   2772 			xhci_op_write_4(sc, port, v | XHCI_PS_CEC);
   2773 			break;
   2774 		default:
   2775 			return -1;
   2776 		}
   2777 		break;
   2778 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
   2779 		if (len == 0)
   2780 			break;
   2781 		if ((value & 0xff) != 0) {
   2782 			return -1;
   2783 		}
   2784 		usb_hub_descriptor_t hubd;
   2785 
   2786 		totlen = min(buflen, sizeof(hubd));
   2787 		memcpy(&hubd, buf, totlen);
   2788 		hubd.bNbrPorts = sc->sc_maxports;
   2789 		USETW(hubd.wHubCharacteristics, UHD_PWR_NO_SWITCH);
   2790 		hubd.bPwrOn2PwrGood = 200;
   2791 		for (i = 0, l = sc->sc_maxports; l > 0; i++, l -= 8)
   2792 			hubd.DeviceRemovable[i++] = 0; /* XXX can't find out? */
   2793 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
   2794 		totlen = min(totlen, hubd.bDescLength);
   2795 		memcpy(buf, &hubd, totlen);
   2796 		break;
   2797 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
   2798 		if (len != 4) {
   2799 			return -1;
   2800 		}
   2801 		memset(buf, 0, len); /* ? XXX */
   2802 		totlen = len;
   2803 		break;
   2804 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
   2805 		DPRINTFN(8, "get port status i=%d", index, 0, 0, 0);
   2806 		if (index < 1 || index > sc->sc_maxports) {
   2807 			return -1;
   2808 		}
   2809 		if (len != 4) {
   2810 			return -1;
   2811 		}
   2812 		v = xhci_op_read_4(sc, XHCI_PORTSC(index));
   2813 		DPRINTFN(4, "getrhportsc %d %08x", index, v, 0, 0);
   2814 		i = xhci_xspeed2psspeed(XHCI_PS_SPEED_GET(v));
   2815 		if (v & XHCI_PS_CCS)	i |= UPS_CURRENT_CONNECT_STATUS;
   2816 		if (v & XHCI_PS_PED)	i |= UPS_PORT_ENABLED;
   2817 		if (v & XHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
   2818 		//if (v & XHCI_PS_SUSP)	i |= UPS_SUSPEND;
   2819 		if (v & XHCI_PS_PR)	i |= UPS_RESET;
   2820 		if (v & XHCI_PS_PP) {
   2821 			if (i & UPS_OTHER_SPEED)
   2822 					i |= UPS_PORT_POWER_SS;
   2823 			else
   2824 					i |= UPS_PORT_POWER;
   2825 		}
   2826 		if (i & UPS_OTHER_SPEED)
   2827 			i |= UPS_PORT_LS_SET(XHCI_PS_PLS_GET(v));
   2828 		USETW(ps.wPortStatus, i);
   2829 		i = 0;
   2830 		if (v & XHCI_PS_CSC)    i |= UPS_C_CONNECT_STATUS;
   2831 		if (v & XHCI_PS_PEC)    i |= UPS_C_PORT_ENABLED;
   2832 		if (v & XHCI_PS_OCC)    i |= UPS_C_OVERCURRENT_INDICATOR;
   2833 		if (v & XHCI_PS_PRC)	i |= UPS_C_PORT_RESET;
   2834 		if (v & XHCI_PS_WRC)	i |= UPS_C_BH_PORT_RESET;
   2835 		if (v & XHCI_PS_PLC)	i |= UPS_C_PORT_LINK_STATE;
   2836 		if (v & XHCI_PS_CEC)	i |= UPS_C_PORT_CONFIG_ERROR;
   2837 		USETW(ps.wPortChange, i);
   2838 		totlen = min(len, sizeof(ps));
   2839 		memcpy(buf, &ps, totlen);
   2840 		break;
   2841 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
   2842 		return -1;
   2843 	case C(UR_SET_HUB_DEPTH, UT_WRITE_CLASS_DEVICE):
   2844 		break;
   2845 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
   2846 		break;
   2847 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER): {
   2848 		int optval = (index >> 8) & 0xff;
   2849 		index &= 0xff;
   2850 		if (index < 1 || index > sc->sc_maxports) {
   2851 			return -1;
   2852 		}
   2853 		port = XHCI_PORTSC(index);
   2854 		v = xhci_op_read_4(sc, port);
   2855 		DPRINTFN(4, "portsc=0x%08x", v, 0, 0, 0);
   2856 		v &= ~XHCI_PS_CLEAR;
   2857 		switch (value) {
   2858 		case UHF_PORT_ENABLE:
   2859 			xhci_op_write_4(sc, port, v | XHCI_PS_PED);
   2860 			break;
   2861 		case UHF_PORT_SUSPEND:
   2862 			/* XXX suspend */
   2863 			break;
   2864 		case UHF_PORT_RESET:
   2865 			v &= ~ (XHCI_PS_PED | XHCI_PS_PR);
   2866 			xhci_op_write_4(sc, port, v | XHCI_PS_PR);
   2867 			/* Wait for reset to complete. */
   2868 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
   2869 			if (sc->sc_dying) {
   2870 				return -1;
   2871 			}
   2872 			v = xhci_op_read_4(sc, port);
   2873 			if (v & XHCI_PS_PR) {
   2874 				xhci_op_write_4(sc, port, v & ~XHCI_PS_PR);
   2875 				usb_delay_ms(&sc->sc_bus, 10);
   2876 				/* XXX */
   2877 			}
   2878 			break;
   2879 		case UHF_PORT_POWER:
   2880 			/* XXX power control */
   2881 			break;
   2882 		/* XXX more */
   2883 		case UHF_C_PORT_RESET:
   2884 			xhci_op_write_4(sc, port, v | XHCI_PS_PRC);
   2885 			break;
   2886 		case UHF_PORT_U1_TIMEOUT:
   2887 			if (USB_IS_SS(xhci_xspeed2speed(XHCI_PS_SPEED_GET(v)))){
   2888 				return -1;
   2889 			}
   2890 			port = XHCI_PORTPMSC(index);
   2891 			v = xhci_op_read_4(sc, port);
   2892 			v &= ~XHCI_PM3_U1TO_SET(0xff);
   2893 			v |= XHCI_PM3_U1TO_SET(optval);
   2894 			xhci_op_write_4(sc, port, v);
   2895 			break;
   2896 		case UHF_PORT_U2_TIMEOUT:
   2897 			if (USB_IS_SS(xhci_xspeed2speed(XHCI_PS_SPEED_GET(v)))){
   2898 				return -1;
   2899 			}
   2900 			port = XHCI_PORTPMSC(index);
   2901 			v = xhci_op_read_4(sc, port);
   2902 			v &= ~XHCI_PM3_U2TO_SET(0xff);
   2903 			v |= XHCI_PM3_U2TO_SET(optval);
   2904 			xhci_op_write_4(sc, port, v);
   2905 			break;
   2906 		default:
   2907 			return -1;
   2908 		}
   2909 	}
   2910 		break;
   2911 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
   2912 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
   2913 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
   2914 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
   2915 		break;
   2916 	default:
   2917 		/* default from usbroothub */
   2918 		return buflen;
   2919 	}
   2920 
   2921 	return totlen;
   2922 }
   2923 
   2924 /* root hub interrupt */
   2925 
   2926 static usbd_status
   2927 xhci_root_intr_transfer(struct usbd_xfer *xfer)
   2928 {
   2929 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   2930 	usbd_status err;
   2931 
   2932 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2933 
   2934 	/* Insert last in queue. */
   2935 	mutex_enter(&sc->sc_lock);
   2936 	err = usb_insert_transfer(xfer);
   2937 	mutex_exit(&sc->sc_lock);
   2938 	if (err)
   2939 		return err;
   2940 
   2941 	/* Pipe isn't running, start first */
   2942 	return xhci_root_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
   2943 }
   2944 
   2945 /* Wait for roothub port status/change */
   2946 static usbd_status
   2947 xhci_root_intr_start(struct usbd_xfer *xfer)
   2948 {
   2949 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   2950 
   2951 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2952 
   2953 	if (sc->sc_dying)
   2954 		return USBD_IOERROR;
   2955 
   2956 	mutex_enter(&sc->sc_lock);
   2957 	sc->sc_intrxfer = xfer;
   2958 	mutex_exit(&sc->sc_lock);
   2959 
   2960 	return USBD_IN_PROGRESS;
   2961 }
   2962 
   2963 static void
   2964 xhci_root_intr_abort(struct usbd_xfer *xfer)
   2965 {
   2966 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   2967 
   2968 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2969 
   2970 	KASSERT(mutex_owned(&sc->sc_lock));
   2971 	KASSERT(xfer->ux_pipe->up_intrxfer == xfer);
   2972 
   2973 	sc->sc_intrxfer = NULL;
   2974 
   2975 	xfer->ux_status = USBD_CANCELLED;
   2976 	usb_transfer_complete(xfer);
   2977 }
   2978 
   2979 static void
   2980 xhci_root_intr_close(struct usbd_pipe *pipe)
   2981 {
   2982 	struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   2983 
   2984 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2985 
   2986 	KASSERT(mutex_owned(&sc->sc_lock));
   2987 
   2988 	sc->sc_intrxfer = NULL;
   2989 }
   2990 
   2991 static void
   2992 xhci_root_intr_done(struct usbd_xfer *xfer)
   2993 {
   2994 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   2995 
   2996 	xfer->ux_hcpriv = NULL;
   2997 }
   2998 
   2999 /* -------------- */
   3000 /* device control */
   3001 
   3002 static usbd_status
   3003 xhci_device_ctrl_transfer(struct usbd_xfer *xfer)
   3004 {
   3005 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3006 	usbd_status err;
   3007 
   3008 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3009 
   3010 	/* Insert last in queue. */
   3011 	mutex_enter(&sc->sc_lock);
   3012 	err = usb_insert_transfer(xfer);
   3013 	mutex_exit(&sc->sc_lock);
   3014 	if (err)
   3015 		return err;
   3016 
   3017 	/* Pipe isn't running, start first */
   3018 	return xhci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
   3019 }
   3020 
   3021 static usbd_status
   3022 xhci_device_ctrl_start(struct usbd_xfer *xfer)
   3023 {
   3024 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3025 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   3026 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   3027 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
   3028 	struct xhci_xfer * const xx = (void *)xfer;
   3029 	usb_device_request_t * const req = &xfer->ux_request;
   3030 	const bool isread = UT_GET_DIR(req->bmRequestType) == UT_READ;
   3031 	const uint32_t len = UGETW(req->wLength);
   3032 	usb_dma_t * const dma = &xfer->ux_dmabuf;
   3033 	uint64_t parameter;
   3034 	uint32_t status;
   3035 	uint32_t control;
   3036 	u_int i;
   3037 
   3038 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3039 	DPRINTFN(12, "req: %04x %04x %04x %04x",
   3040 	    req->bmRequestType | (req->bRequest << 8), UGETW(req->wValue),
   3041 	    UGETW(req->wIndex), UGETW(req->wLength));
   3042 
   3043 	/* XXX */
   3044 	if (tr->is_halted) {
   3045 		DPRINTFN(1, "ctrl xfer %p halted: slot %u dci %u",
   3046 		    xfer, xs->xs_idx, dci, 0);
   3047 		xhci_reset_endpoint(xfer->ux_pipe);
   3048 		tr->is_halted = false;
   3049 		xhci_set_dequeue(xfer->ux_pipe);
   3050 	}
   3051 
   3052 	/* we rely on the bottom bits for extra info */
   3053 	KASSERT(((uintptr_t)xfer & 0x3) == 0x0);
   3054 
   3055 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) != 0);
   3056 
   3057 	i = 0;
   3058 
   3059 	/* setup phase */
   3060 	memcpy(&parameter, req, sizeof(*req));
   3061 	parameter = le64toh(parameter);
   3062 	status = XHCI_TRB_2_IRQ_SET(0) | XHCI_TRB_2_BYTES_SET(sizeof(*req));
   3063 	control = ((len == 0) ? XHCI_TRB_3_TRT_NONE :
   3064 	     (isread ? XHCI_TRB_3_TRT_IN : XHCI_TRB_3_TRT_OUT)) |
   3065 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
   3066 	    XHCI_TRB_3_IDT_BIT;
   3067 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3068 
   3069 	if (len == 0)
   3070 		goto no_data;
   3071 
   3072 	/* data phase */
   3073 	parameter = DMAADDR(dma, 0);
   3074 	KASSERT(len <= 0x10000);
   3075 	status = XHCI_TRB_2_IRQ_SET(0) |
   3076 	    XHCI_TRB_2_TDSZ_SET(1) |
   3077 	    XHCI_TRB_2_BYTES_SET(len);
   3078 	control = (isread ? XHCI_TRB_3_DIR_IN : 0) |
   3079 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE) |
   3080 	    XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_ENT_BIT;
   3081 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3082 
   3083 	parameter = (uintptr_t)xfer | 0x3;
   3084 	status = XHCI_TRB_2_IRQ_SET(0);
   3085 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVENT_DATA) |
   3086 	    XHCI_TRB_3_IOC_BIT;
   3087 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3088 
   3089 no_data:
   3090 	parameter = 0;
   3091 	status = XHCI_TRB_2_IRQ_SET(0);
   3092 	/* the status stage has inverted direction */
   3093 	control = ((isread && (len > 0)) ? 0 : XHCI_TRB_3_DIR_IN) |
   3094 	    XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE) |
   3095 	    XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_ENT_BIT;
   3096 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3097 
   3098 	parameter = (uintptr_t)xfer | 0x0;
   3099 	status = XHCI_TRB_2_IRQ_SET(0);
   3100 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVENT_DATA) |
   3101 	    XHCI_TRB_3_IOC_BIT;
   3102 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3103 
   3104 	mutex_enter(&tr->xr_lock);
   3105 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
   3106 	mutex_exit(&tr->xr_lock);
   3107 
   3108 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
   3109 
   3110 	if (xfer->ux_timeout && !sc->sc_bus.ub_usepolling) {
   3111 		callout_reset(&xfer->ux_callout, mstohz(xfer->ux_timeout),
   3112 		    xhci_timeout, xfer);
   3113 	}
   3114 
   3115 	if (sc->sc_bus.ub_usepolling) {
   3116 		DPRINTFN(1, "polling", 0, 0, 0, 0);
   3117 		//xhci_waitintr(sc, xfer);
   3118 	}
   3119 
   3120 	return USBD_IN_PROGRESS;
   3121 }
   3122 
   3123 static void
   3124 xhci_device_ctrl_done(struct usbd_xfer *xfer)
   3125 {
   3126 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3127 
   3128 	callout_stop(&xfer->ux_callout); /* XXX wrong place */
   3129 
   3130 }
   3131 
   3132 static void
   3133 xhci_device_ctrl_abort(struct usbd_xfer *xfer)
   3134 {
   3135 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3136 
   3137 	xhci_abort_xfer(xfer, USBD_CANCELLED);
   3138 }
   3139 
   3140 static void
   3141 xhci_device_ctrl_close(struct usbd_pipe *pipe)
   3142 {
   3143 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3144 
   3145 	xhci_close_pipe(pipe);
   3146 }
   3147 
   3148 /* ------------------ */
   3149 /* device isochronous */
   3150 
   3151 /* ----------- */
   3152 /* device bulk */
   3153 
   3154 static usbd_status
   3155 xhci_device_bulk_transfer(struct usbd_xfer *xfer)
   3156 {
   3157 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3158 	usbd_status err;
   3159 
   3160 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3161 
   3162 	/* Insert last in queue. */
   3163 	mutex_enter(&sc->sc_lock);
   3164 	err = usb_insert_transfer(xfer);
   3165 	mutex_exit(&sc->sc_lock);
   3166 	if (err)
   3167 		return err;
   3168 
   3169 	/*
   3170 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
   3171 	 * so start it first.
   3172 	 */
   3173 	return xhci_device_bulk_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
   3174 }
   3175 
   3176 static usbd_status
   3177 xhci_device_bulk_start(struct usbd_xfer *xfer)
   3178 {
   3179 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3180 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   3181 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   3182 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
   3183 	struct xhci_xfer * const xx = (void *)xfer;
   3184 	const uint32_t len = xfer->ux_length;
   3185 	usb_dma_t * const dma = &xfer->ux_dmabuf;
   3186 	uint64_t parameter;
   3187 	uint32_t status;
   3188 	uint32_t control;
   3189 	u_int i = 0;
   3190 
   3191 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3192 
   3193 	DPRINTFN(15, "%p slot %u dci %u", xfer, xs->xs_idx, dci, 0);
   3194 
   3195 	if (sc->sc_dying)
   3196 		return USBD_IOERROR;
   3197 
   3198 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) == 0);
   3199 
   3200 	parameter = DMAADDR(dma, 0);
   3201 	/*
   3202 	 * XXX: (dsl) The physical buffer must not cross a 64k boundary.
   3203 	 * If the user supplied buffer crosses such a boundary then 2
   3204 	 * (or more) TRB should be used.
   3205 	 * If multiple TRB are used the td_size field must be set correctly.
   3206 	 * For v1.0 devices (like ivy bridge) this is the number of usb data
   3207 	 * blocks needed to complete the transfer.
   3208 	 * Setting it to 1 in the last TRB causes an extra zero-length
   3209 	 * data block be sent.
   3210 	 * The earlier documentation differs, I don't know how it behaves.
   3211 	 */
   3212 	KASSERT(len <= 0x10000);
   3213 	status = XHCI_TRB_2_IRQ_SET(0) |
   3214 	    XHCI_TRB_2_TDSZ_SET(1) |
   3215 	    XHCI_TRB_2_BYTES_SET(len);
   3216 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL) |
   3217 	    XHCI_TRB_3_ISP_BIT | XHCI_TRB_3_IOC_BIT;
   3218 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3219 
   3220 	mutex_enter(&tr->xr_lock);
   3221 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
   3222 	mutex_exit(&tr->xr_lock);
   3223 
   3224 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
   3225 
   3226 	if (sc->sc_bus.ub_usepolling) {
   3227 		DPRINTFN(1, "polling", 0, 0, 0, 0);
   3228 		//xhci_waitintr(sc, xfer);
   3229 	}
   3230 
   3231 	return USBD_IN_PROGRESS;
   3232 }
   3233 
   3234 static void
   3235 xhci_device_bulk_done(struct usbd_xfer *xfer)
   3236 {
   3237 #ifdef USB_DEBUG
   3238 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   3239 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   3240 #endif
   3241 	const u_int endpt = xfer->ux_pipe->up_endpoint->ue_edesc->bEndpointAddress;
   3242 	const bool isread = UE_GET_DIR(endpt) == UE_DIR_IN;
   3243 
   3244 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3245 
   3246 	DPRINTFN(15, "%p slot %u dci %u", xfer, xs->xs_idx, dci, 0);
   3247 
   3248 	callout_stop(&xfer->ux_callout); /* XXX wrong place */
   3249 
   3250 	usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
   3251 	    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
   3252 }
   3253 
   3254 static void
   3255 xhci_device_bulk_abort(struct usbd_xfer *xfer)
   3256 {
   3257 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3258 
   3259 	xhci_abort_xfer(xfer, USBD_CANCELLED);
   3260 }
   3261 
   3262 static void
   3263 xhci_device_bulk_close(struct usbd_pipe *pipe)
   3264 {
   3265 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3266 
   3267 	xhci_close_pipe(pipe);
   3268 }
   3269 
   3270 /* ---------------- */
   3271 /* device interrupt */
   3272 
   3273 static usbd_status
   3274 xhci_device_intr_transfer(struct usbd_xfer *xfer)
   3275 {
   3276 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3277 	usbd_status err;
   3278 
   3279 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3280 
   3281 	/* Insert last in queue. */
   3282 	mutex_enter(&sc->sc_lock);
   3283 	err = usb_insert_transfer(xfer);
   3284 	mutex_exit(&sc->sc_lock);
   3285 	if (err)
   3286 		return err;
   3287 
   3288 	/*
   3289 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
   3290 	 * so start it first.
   3291 	 */
   3292 	return xhci_device_intr_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
   3293 }
   3294 
   3295 static usbd_status
   3296 xhci_device_intr_start(struct usbd_xfer *xfer)
   3297 {
   3298 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3299 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   3300 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   3301 	struct xhci_ring * const tr = &xs->xs_ep[dci].xe_tr;
   3302 	struct xhci_xfer * const xx = (void *)xfer;
   3303 	const uint32_t len = xfer->ux_length;
   3304 	usb_dma_t * const dma = &xfer->ux_dmabuf;
   3305 	uint64_t parameter;
   3306 	uint32_t status;
   3307 	uint32_t control;
   3308 	u_int i = 0;
   3309 
   3310 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3311 
   3312 	DPRINTFN(15, "%p slot %u dci %u", xfer, xs->xs_idx, dci, 0);
   3313 
   3314 	if (sc->sc_dying)
   3315 		return USBD_IOERROR;
   3316 
   3317 	KASSERT((xfer->ux_rqflags & URQ_REQUEST) == 0);
   3318 
   3319 	parameter = DMAADDR(dma, 0);
   3320 	KASSERT(len <= 0x10000);
   3321 	status = XHCI_TRB_2_IRQ_SET(0) |
   3322 	    XHCI_TRB_2_TDSZ_SET(1) |
   3323 	    XHCI_TRB_2_BYTES_SET(len);
   3324 	control = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL) |
   3325 	    XHCI_TRB_3_ISP_BIT | XHCI_TRB_3_IOC_BIT;
   3326 	xhci_trb_put(&xx->xx_trb[i++], parameter, status, control);
   3327 
   3328 	mutex_enter(&tr->xr_lock);
   3329 	xhci_ring_put(sc, tr, xfer, xx->xx_trb, i);
   3330 	mutex_exit(&tr->xr_lock);
   3331 
   3332 	xhci_db_write_4(sc, XHCI_DOORBELL(xs->xs_idx), dci);
   3333 
   3334 	if (sc->sc_bus.ub_usepolling) {
   3335 		DPRINTFN(1, "polling", 0, 0, 0, 0);
   3336 		//xhci_waitintr(sc, xfer);
   3337 	}
   3338 
   3339 	return USBD_IN_PROGRESS;
   3340 }
   3341 
   3342 static void
   3343 xhci_device_intr_done(struct usbd_xfer *xfer)
   3344 {
   3345 	struct xhci_softc * const sc __diagused =
   3346 		xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3347 #ifdef USB_DEBUG
   3348 	struct xhci_slot * const xs = xfer->ux_pipe->up_dev->ud_hcpriv;
   3349 	const u_int dci = xhci_ep_get_dci(xfer->ux_pipe->up_endpoint->ue_edesc);
   3350 #endif
   3351 	const u_int endpt = xfer->ux_pipe->up_endpoint->ue_edesc->bEndpointAddress;
   3352 	const bool isread = UE_GET_DIR(endpt) == UE_DIR_IN;
   3353 
   3354 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3355 
   3356 	DPRINTFN(15, "%p slot %u dci %u", xfer, xs->xs_idx, dci, 0);
   3357 
   3358 	KASSERT(sc->sc_bus.ub_usepolling || mutex_owned(&sc->sc_lock));
   3359 
   3360 	usb_syncmem(&xfer->ux_dmabuf, 0, xfer->ux_length,
   3361 	    isread ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
   3362 
   3363 #if 0
   3364 	device_printf(sc->sc_dev, "");
   3365 	for (size_t i = 0; i < xfer->ux_length; i++) {
   3366 		printf(" %02x", ((uint8_t const *)xfer->ux_buffer)[i]);
   3367 	}
   3368 	printf("\n");
   3369 #endif
   3370 
   3371 	if (xfer->ux_pipe->up_repeat) {
   3372 		xfer->ux_status = xhci_device_intr_start(xfer);
   3373 	} else {
   3374 		callout_stop(&xfer->ux_callout); /* XXX */
   3375 	}
   3376 
   3377 }
   3378 
   3379 static void
   3380 xhci_device_intr_abort(struct usbd_xfer *xfer)
   3381 {
   3382 	struct xhci_softc * const sc __diagused =
   3383 				    xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3384 
   3385 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3386 
   3387 	KASSERT(mutex_owned(&sc->sc_lock));
   3388 	DPRINTFN(15, "%p", xfer, 0, 0, 0);
   3389 	KASSERT(xfer->ux_pipe->up_intrxfer == xfer);
   3390 	xhci_abort_xfer(xfer, USBD_CANCELLED);
   3391 }
   3392 
   3393 static void
   3394 xhci_device_intr_close(struct usbd_pipe *pipe)
   3395 {
   3396 	//struct xhci_softc * const sc = pipe->up_dev->ud_bus->ub_hcpriv;
   3397 
   3398 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3399 	DPRINTFN(15, "%p", pipe, 0, 0, 0);
   3400 
   3401 	xhci_close_pipe(pipe);
   3402 }
   3403 
   3404 /* ------------ */
   3405 
   3406 static void
   3407 xhci_timeout(void *addr)
   3408 {
   3409 	struct xhci_xfer * const xx = addr;
   3410 	struct usbd_xfer * const xfer = &xx->xx_xfer;
   3411 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3412 
   3413 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3414 
   3415 	if (sc->sc_dying) {
   3416 		return;
   3417 	}
   3418 
   3419 	usb_init_task(&xx->xx_abort_task, xhci_timeout_task, addr,
   3420 	    USB_TASKQ_MPSAFE);
   3421 	usb_add_task(xx->xx_xfer.ux_pipe->up_dev, &xx->xx_abort_task,
   3422 	    USB_TASKQ_HC);
   3423 }
   3424 
   3425 static void
   3426 xhci_timeout_task(void *addr)
   3427 {
   3428 	struct usbd_xfer * const xfer = addr;
   3429 	struct xhci_softc * const sc = xfer->ux_pipe->up_dev->ud_bus->ub_hcpriv;
   3430 
   3431 	XHCIHIST_FUNC(); XHCIHIST_CALLED();
   3432 
   3433 	mutex_enter(&sc->sc_lock);
   3434 #if 0
   3435 	xhci_abort_xfer(xfer, USBD_TIMEOUT);
   3436 #else
   3437 	xfer->ux_status = USBD_TIMEOUT;
   3438 	usb_transfer_complete(xfer);
   3439 #endif
   3440 	mutex_exit(&sc->sc_lock);
   3441 }
   3442