The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/usb/controller/xhci.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /* $FreeBSD$ */
    2 /*-
    3  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
    4  *
    5  * Copyright (c) 2010-2022 Hans Petter Selasky
    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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26  * SUCH DAMAGE.
   27  */
   28 
   29 /*
   30  * USB eXtensible Host Controller Interface, a.k.a. USB 3.0 controller.
   31  *
   32  * The XHCI 1.0 spec can be found at
   33  * http://www.intel.com/technology/usb/download/xHCI_Specification_for_USB.pdf
   34  * and the USB 3.0 spec at
   35  * http://www.usb.org/developers/docs/usb_30_spec_060910.zip
   36  */
   37 
   38 /*
   39  * A few words about the design implementation: This driver emulates
   40  * the concept about TDs which is found in EHCI specification. This
   41  * way we achieve that the USB controller drivers look similar to
   42  * eachother which makes it easier to understand the code.
   43  */
   44 
   45 #ifdef USB_GLOBAL_INCLUDE_FILE
   46 #include USB_GLOBAL_INCLUDE_FILE
   47 #else
   48 #include <sys/stdint.h>
   49 #include <sys/stddef.h>
   50 #include <sys/param.h>
   51 #include <sys/queue.h>
   52 #include <sys/types.h>
   53 #include <sys/systm.h>
   54 #include <sys/kernel.h>
   55 #include <sys/bus.h>
   56 #include <sys/module.h>
   57 #include <sys/lock.h>
   58 #include <sys/mutex.h>
   59 #include <sys/condvar.h>
   60 #include <sys/sysctl.h>
   61 #include <sys/sx.h>
   62 #include <sys/unistd.h>
   63 #include <sys/callout.h>
   64 #include <sys/malloc.h>
   65 #include <sys/priv.h>
   66 
   67 #include <dev/usb/usb.h>
   68 #include <dev/usb/usbdi.h>
   69 
   70 #define USB_DEBUG_VAR xhcidebug
   71 
   72 #include <dev/usb/usb_core.h>
   73 #include <dev/usb/usb_debug.h>
   74 #include <dev/usb/usb_busdma.h>
   75 #include <dev/usb/usb_process.h>
   76 #include <dev/usb/usb_transfer.h>
   77 #include <dev/usb/usb_device.h>
   78 #include <dev/usb/usb_hub.h>
   79 #include <dev/usb/usb_util.h>
   80 
   81 #include <dev/usb/usb_controller.h>
   82 #include <dev/usb/usb_bus.h>
   83 #endif                  /* USB_GLOBAL_INCLUDE_FILE */
   84 
   85 #include <dev/usb/controller/xhci.h>
   86 #include <dev/usb/controller/xhcireg.h>
   87 
   88 #define XHCI_BUS2SC(bus) \
   89         __containerof(bus, struct xhci_softc, sc_bus)
   90 
   91 #define XHCI_GET_CTX(sc, which, field, ptr) \
   92         ((sc)->sc_ctx_is_64_byte ? \
   93             &((struct which##64 *)(ptr))->field.ctx : \
   94             &((struct which *)(ptr))->field)
   95 
   96 static SYSCTL_NODE(_hw_usb, OID_AUTO, xhci, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
   97     "USB XHCI");
   98 
   99 static int xhcistreams;
  100 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, streams, CTLFLAG_RWTUN,
  101     &xhcistreams, 0, "Set to enable streams mode support");
  102 
  103 static int xhcictlquirk = 1;
  104 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, ctlquirk, CTLFLAG_RWTUN,
  105     &xhcictlquirk, 0, "Set to enable control endpoint quirk");
  106 
  107 static int xhcidcepquirk;
  108 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, dcepquirk, CTLFLAG_RWTUN,
  109     &xhcidcepquirk, 0, "Set to disable endpoint deconfigure command");
  110 
  111 #ifdef USB_DEBUG
  112 static int xhcidebug;
  113 static int xhciroute;
  114 static int xhcipolling;
  115 static int xhcidma32;
  116 static int xhcictlstep;
  117 
  118 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, debug, CTLFLAG_RWTUN,
  119     &xhcidebug, 0, "Debug level");
  120 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, xhci_port_route, CTLFLAG_RWTUN,
  121     &xhciroute, 0, "Routing bitmap for switching EHCI ports to the XHCI controller");
  122 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, use_polling, CTLFLAG_RWTUN,
  123     &xhcipolling, 0, "Set to enable software interrupt polling for the XHCI controller");
  124 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, dma32, CTLFLAG_RWTUN,
  125     &xhcidma32, 0, "Set to only use 32-bit DMA for the XHCI controller");
  126 SYSCTL_INT(_hw_usb_xhci, OID_AUTO, ctlstep, CTLFLAG_RWTUN,
  127     &xhcictlstep, 0, "Set to enable control endpoint status stage stepping");
  128 #else
  129 #define xhciroute 0
  130 #define xhcidma32 0
  131 #define xhcictlstep 0
  132 #endif
  133 
  134 #define XHCI_INTR_ENDPT 1
  135 
  136 struct xhci_std_temp {
  137         struct xhci_softc       *sc;
  138         struct usb_page_cache   *pc;
  139         struct xhci_td          *td;
  140         struct xhci_td          *td_next;
  141         uint32_t                len;
  142         uint32_t                offset;
  143         uint32_t                max_packet_size;
  144         uint32_t                average;
  145         uint32_t                isoc_frame;
  146         uint16_t                isoc_delta;
  147         uint8_t                 shortpkt;
  148         uint8_t                 multishort;
  149         uint8_t                 last_frame;
  150         uint8_t                 trb_type;
  151         uint8_t                 direction;
  152         uint8_t                 tbc;
  153         uint8_t                 tlbpc;
  154         uint8_t                 step_td;
  155         uint8_t                 do_isoc_sync;
  156 };
  157 
  158 static void     xhci_do_poll(struct usb_bus *);
  159 static void     xhci_device_done(struct usb_xfer *, usb_error_t);
  160 static void     xhci_root_intr(struct xhci_softc *);
  161 static void     xhci_free_device_ext(struct usb_device *);
  162 static struct xhci_endpoint_ext *xhci_get_endpoint_ext(struct usb_device *,
  163                     struct usb_endpoint_descriptor *);
  164 static usb_proc_callback_t xhci_configure_msg;
  165 static usb_error_t xhci_configure_device(struct usb_device *);
  166 static usb_error_t xhci_configure_endpoint(struct usb_device *,
  167                    struct usb_endpoint_descriptor *, struct xhci_endpoint_ext *,
  168                    uint16_t, uint8_t, uint8_t, uint8_t, uint16_t, uint16_t,
  169                    uint8_t);
  170 static usb_error_t xhci_configure_mask(struct usb_device *,
  171                     uint32_t, uint8_t);
  172 static usb_error_t xhci_cmd_evaluate_ctx(struct xhci_softc *,
  173                     uint64_t, uint8_t);
  174 static void xhci_endpoint_doorbell(struct usb_xfer *);
  175 
  176 static const struct usb_bus_methods xhci_bus_methods;
  177 
  178 #ifdef USB_DEBUG
  179 static void
  180 xhci_dump_trb(struct xhci_trb *trb)
  181 {
  182         DPRINTFN(5, "trb = %p\n", trb);
  183         DPRINTFN(5, "qwTrb0 = 0x%016llx\n", (long long)le64toh(trb->qwTrb0));
  184         DPRINTFN(5, "dwTrb2 = 0x%08x\n", le32toh(trb->dwTrb2));
  185         DPRINTFN(5, "dwTrb3 = 0x%08x\n", le32toh(trb->dwTrb3));
  186 }
  187 
  188 static void
  189 xhci_dump_endpoint(struct xhci_endp_ctx *pep)
  190 {
  191         DPRINTFN(5, "pep = %p\n", pep);
  192         DPRINTFN(5, "dwEpCtx0=0x%08x\n", le32toh(pep->dwEpCtx0));
  193         DPRINTFN(5, "dwEpCtx1=0x%08x\n", le32toh(pep->dwEpCtx1));
  194         DPRINTFN(5, "qwEpCtx2=0x%016llx\n", (long long)le64toh(pep->qwEpCtx2));
  195         DPRINTFN(5, "dwEpCtx4=0x%08x\n", le32toh(pep->dwEpCtx4));
  196         DPRINTFN(5, "dwEpCtx5=0x%08x\n", le32toh(pep->dwEpCtx5));
  197         DPRINTFN(5, "dwEpCtx6=0x%08x\n", le32toh(pep->dwEpCtx6));
  198         DPRINTFN(5, "dwEpCtx7=0x%08x\n", le32toh(pep->dwEpCtx7));
  199 }
  200 
  201 static void
  202 xhci_dump_device(struct xhci_slot_ctx *psl)
  203 {
  204         DPRINTFN(5, "psl = %p\n", psl);
  205         DPRINTFN(5, "dwSctx0=0x%08x\n", le32toh(psl->dwSctx0));
  206         DPRINTFN(5, "dwSctx1=0x%08x\n", le32toh(psl->dwSctx1));
  207         DPRINTFN(5, "dwSctx2=0x%08x\n", le32toh(psl->dwSctx2));
  208         DPRINTFN(5, "dwSctx3=0x%08x\n", le32toh(psl->dwSctx3));
  209 }
  210 #endif
  211 
  212 uint8_t
  213 xhci_use_polling(void)
  214 {
  215 #ifdef USB_DEBUG
  216         return (xhcipolling != 0);
  217 #else
  218         return (0);
  219 #endif
  220 }
  221 
  222 static void
  223 xhci_iterate_hw_softc(struct usb_bus *bus, usb_bus_mem_sub_cb_t *cb)
  224 {
  225         struct xhci_softc *sc = XHCI_BUS2SC(bus);
  226         uint16_t i;
  227 
  228         cb(bus, &sc->sc_hw.root_pc, &sc->sc_hw.root_pg,
  229            sizeof(struct xhci_hw_root), XHCI_PAGE_SIZE);
  230 
  231         cb(bus, &sc->sc_hw.ctx_pc, &sc->sc_hw.ctx_pg,
  232            sizeof(struct xhci_dev_ctx_addr), XHCI_PAGE_SIZE);
  233 
  234         for (i = 0; i != sc->sc_noscratch; i++) {
  235                 cb(bus, &sc->sc_hw.scratch_pc[i], &sc->sc_hw.scratch_pg[i],
  236                     XHCI_PAGE_SIZE, XHCI_PAGE_SIZE);
  237         }
  238 }
  239 
  240 static int
  241 xhci_reset_command_queue_locked(struct xhci_softc *sc)
  242 {
  243         struct usb_page_search buf_res;
  244         struct xhci_hw_root *phwr;
  245         uint64_t addr;
  246         uint32_t temp;
  247 
  248         DPRINTF("\n");
  249 
  250         temp = XREAD4(sc, oper, XHCI_CRCR_LO);
  251         if (temp & XHCI_CRCR_LO_CRR) {
  252                 DPRINTF("Command ring running\n");
  253                 temp &= ~(XHCI_CRCR_LO_CS | XHCI_CRCR_LO_CA);
  254 
  255                 /*
  256                  * Try to abort the last command as per section
  257                  * 4.6.1.2 "Aborting a Command" of the XHCI
  258                  * specification:
  259                  */
  260 
  261                 /* stop and cancel */
  262                 XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CS);
  263                 XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
  264 
  265                 XWRITE4(sc, oper, XHCI_CRCR_LO, temp | XHCI_CRCR_LO_CA);
  266                 XWRITE4(sc, oper, XHCI_CRCR_HI, 0);
  267 
  268                 /* wait 250ms */
  269                 usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 4);
  270 
  271                 /* check if command ring is still running */
  272                 temp = XREAD4(sc, oper, XHCI_CRCR_LO);
  273                 if (temp & XHCI_CRCR_LO_CRR) {
  274                         DPRINTF("Comand ring still running\n");
  275                         return (USB_ERR_IOERROR);
  276                 }
  277         }
  278 
  279         /* reset command ring */
  280         sc->sc_command_ccs = 1;
  281         sc->sc_command_idx = 0;
  282 
  283         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
  284 
  285         /* set up command ring control base address */
  286         addr = buf_res.physaddr;
  287         phwr = buf_res.buffer;
  288         addr += __offsetof(struct xhci_hw_root, hwr_commands[0]);
  289 
  290         DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
  291 
  292         memset(phwr->hwr_commands, 0, sizeof(phwr->hwr_commands));
  293         phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
  294 
  295         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
  296 
  297         XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
  298         XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
  299 
  300         return (0);
  301 }
  302 
  303 usb_error_t
  304 xhci_start_controller(struct xhci_softc *sc)
  305 {
  306         struct usb_page_search buf_res;
  307         struct xhci_hw_root *phwr;
  308         struct xhci_dev_ctx_addr *pdctxa;
  309         usb_error_t err;
  310         uint64_t addr;
  311         uint32_t temp;
  312         uint16_t i;
  313 
  314         DPRINTF("\n");
  315 
  316         sc->sc_event_ccs = 1;
  317         sc->sc_event_idx = 0;
  318         sc->sc_command_ccs = 1;
  319         sc->sc_command_idx = 0;
  320 
  321         err = xhci_reset_controller(sc);
  322         if (err)
  323                 return (err);
  324 
  325         /* set up number of device slots */
  326         DPRINTF("CONFIG=0x%08x -> 0x%08x\n",
  327             XREAD4(sc, oper, XHCI_CONFIG), sc->sc_noslot);
  328 
  329         XWRITE4(sc, oper, XHCI_CONFIG, sc->sc_noslot);
  330 
  331         temp = XREAD4(sc, oper, XHCI_USBSTS);
  332 
  333         /* clear interrupts */
  334         XWRITE4(sc, oper, XHCI_USBSTS, temp);
  335         /* disable all device notifications */
  336         XWRITE4(sc, oper, XHCI_DNCTRL, 0);
  337 
  338         /* set up device context base address */
  339         usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
  340         pdctxa = buf_res.buffer;
  341         memset(pdctxa, 0, sizeof(*pdctxa));
  342 
  343         addr = buf_res.physaddr;
  344         addr += __offsetof(struct xhci_dev_ctx_addr, qwSpBufPtr[0]);
  345 
  346         /* slot 0 points to the table of scratchpad pointers */
  347         pdctxa->qwBaaDevCtxAddr[0] = htole64(addr);
  348 
  349         for (i = 0; i != sc->sc_noscratch; i++) {
  350                 struct usb_page_search buf_scp;
  351                 usbd_get_page(&sc->sc_hw.scratch_pc[i], 0, &buf_scp);
  352                 pdctxa->qwSpBufPtr[i] = htole64((uint64_t)buf_scp.physaddr);
  353         }
  354 
  355         addr = buf_res.physaddr;
  356 
  357         XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
  358         XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
  359         XWRITE4(sc, oper, XHCI_DCBAAP_LO, (uint32_t)addr);
  360         XWRITE4(sc, oper, XHCI_DCBAAP_HI, (uint32_t)(addr >> 32));
  361 
  362         /* set up event table size */
  363         DPRINTF("ERSTSZ=0x%08x -> 0x%08x\n",
  364             XREAD4(sc, runt, XHCI_ERSTSZ(0)), sc->sc_erst_max);
  365 
  366         XWRITE4(sc, runt, XHCI_ERSTSZ(0), XHCI_ERSTS_SET(sc->sc_erst_max));
  367 
  368         /* set up interrupt rate */
  369         XWRITE4(sc, runt, XHCI_IMOD(0), sc->sc_imod_default);
  370 
  371         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
  372 
  373         phwr = buf_res.buffer;
  374         addr = buf_res.physaddr;
  375         addr += __offsetof(struct xhci_hw_root, hwr_events[0]);
  376 
  377         /* reset hardware root structure */
  378         memset(phwr, 0, sizeof(*phwr));
  379 
  380         phwr->hwr_ring_seg[0].qwEvrsTablePtr = htole64(addr);
  381         phwr->hwr_ring_seg[0].dwEvrsTableSize = htole32(XHCI_MAX_EVENTS);
  382 
  383         /*
  384          * PR 237666:
  385          *
  386          * According to the XHCI specification, the XWRITE4's to
  387          * XHCI_ERSTBA_LO and _HI lead to the XHCI to copy the
  388          * qwEvrsTablePtr and dwEvrsTableSize values above at that
  389          * time, as the XHCI initializes its event ring support. This
  390          * is before the event ring starts to pay attention to the
  391          * RUN/STOP bit. Thus, make sure the values are observable to
  392          * the XHCI before that point.
  393          */
  394         usb_bus_mem_flush_all(&sc->sc_bus, &xhci_iterate_hw_softc);
  395 
  396         DPRINTF("ERDP(0)=0x%016llx\n", (unsigned long long)addr);
  397 
  398         XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
  399         XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
  400 
  401         addr = buf_res.physaddr;
  402 
  403         DPRINTF("ERSTBA(0)=0x%016llx\n", (unsigned long long)addr);
  404 
  405         XWRITE4(sc, runt, XHCI_ERSTBA_LO(0), (uint32_t)addr);
  406         XWRITE4(sc, runt, XHCI_ERSTBA_HI(0), (uint32_t)(addr >> 32));
  407 
  408         /* set up interrupter registers */
  409         temp = XREAD4(sc, runt, XHCI_IMAN(0));
  410         temp |= XHCI_IMAN_INTR_ENA;
  411         XWRITE4(sc, runt, XHCI_IMAN(0), temp);
  412 
  413         /* set up command ring control base address */
  414         addr = buf_res.physaddr;
  415         addr += __offsetof(struct xhci_hw_root, hwr_commands[0]);
  416 
  417         DPRINTF("CRCR=0x%016llx\n", (unsigned long long)addr);
  418 
  419         XWRITE4(sc, oper, XHCI_CRCR_LO, ((uint32_t)addr) | XHCI_CRCR_LO_RCS);
  420         XWRITE4(sc, oper, XHCI_CRCR_HI, (uint32_t)(addr >> 32));
  421 
  422         phwr->hwr_commands[XHCI_MAX_COMMANDS - 1].qwTrb0 = htole64(addr);
  423 
  424         usb_bus_mem_flush_all(&sc->sc_bus, &xhci_iterate_hw_softc);
  425 
  426         /* Go! */
  427         XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_RS |
  428             XHCI_CMD_INTE | XHCI_CMD_HSEE);
  429 
  430         for (i = 0; i != 100; i++) {
  431                 usb_pause_mtx(NULL, hz / 100);
  432                 temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
  433                 if (!temp)
  434                         break;
  435         }
  436         if (temp) {
  437                 XWRITE4(sc, oper, XHCI_USBCMD, 0);
  438                 device_printf(sc->sc_bus.parent, "Run timeout.\n");
  439                 return (USB_ERR_IOERROR);
  440         }
  441 
  442         /* catch any lost interrupts */
  443         xhci_do_poll(&sc->sc_bus);
  444 
  445         if (sc->sc_port_route != NULL) {
  446                 /* Route all ports to the XHCI by default */
  447                 sc->sc_port_route(sc->sc_bus.parent,
  448                     ~xhciroute, xhciroute);
  449         }
  450         return (0);
  451 }
  452 
  453 usb_error_t
  454 xhci_halt_controller(struct xhci_softc *sc)
  455 {
  456         uint32_t temp;
  457         uint16_t i;
  458 
  459         DPRINTF("\n");
  460 
  461         sc->sc_capa_off = 0;
  462         sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
  463         sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0xF;
  464         sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
  465 
  466         /* Halt controller */
  467         XWRITE4(sc, oper, XHCI_USBCMD, 0);
  468 
  469         for (i = 0; i != 100; i++) {
  470                 usb_pause_mtx(NULL, hz / 100);
  471                 temp = XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_HCH;
  472                 if (temp)
  473                         break;
  474         }
  475 
  476         if (!temp) {
  477                 device_printf(sc->sc_bus.parent, "Controller halt timeout.\n");
  478                 return (USB_ERR_IOERROR);
  479         }
  480         return (0);
  481 }
  482 
  483 usb_error_t
  484 xhci_reset_controller(struct xhci_softc *sc)
  485 {
  486         uint32_t temp = 0;
  487         uint16_t i;
  488 
  489         DPRINTF("\n");
  490 
  491         /* Reset controller */
  492         XWRITE4(sc, oper, XHCI_USBCMD, XHCI_CMD_HCRST);
  493 
  494         for (i = 0; i != 100; i++) {
  495                 usb_pause_mtx(NULL, hz / 100);
  496                 temp = (XREAD4(sc, oper, XHCI_USBCMD) & XHCI_CMD_HCRST) |
  497                     (XREAD4(sc, oper, XHCI_USBSTS) & XHCI_STS_CNR);
  498                 if (!temp)
  499                         break;
  500         }
  501 
  502         if (temp) {
  503                 device_printf(sc->sc_bus.parent, "Controller "
  504                     "reset timeout.\n");
  505                 return (USB_ERR_IOERROR);
  506         }
  507         return (0);
  508 }
  509 
  510 usb_error_t
  511 xhci_init(struct xhci_softc *sc, device_t self, uint8_t dma32)
  512 {
  513         uint32_t temp;
  514 
  515         DPRINTF("\n");
  516 
  517         /* initialize some bus fields */
  518         sc->sc_bus.parent = self;
  519 
  520         /* set the bus revision */
  521         sc->sc_bus.usbrev = USB_REV_3_0;
  522 
  523         /* set up the bus struct */
  524         sc->sc_bus.methods = &xhci_bus_methods;
  525 
  526         /* set up devices array */
  527         sc->sc_bus.devices = sc->sc_devices;
  528         sc->sc_bus.devices_max = XHCI_MAX_DEVICES;
  529 
  530         /* set default cycle state in case of early interrupts */
  531         sc->sc_event_ccs = 1;
  532         sc->sc_command_ccs = 1;
  533 
  534         /* set up bus space offsets */
  535         sc->sc_capa_off = 0;
  536         sc->sc_oper_off = XREAD1(sc, capa, XHCI_CAPLENGTH);
  537         sc->sc_runt_off = XREAD4(sc, capa, XHCI_RTSOFF) & ~0x1F;
  538         sc->sc_door_off = XREAD4(sc, capa, XHCI_DBOFF) & ~0x3;
  539 
  540         DPRINTF("CAPLENGTH=0x%x\n", sc->sc_oper_off);
  541         DPRINTF("RUNTIMEOFFSET=0x%x\n", sc->sc_runt_off);
  542         DPRINTF("DOOROFFSET=0x%x\n", sc->sc_door_off);
  543 
  544         DPRINTF("xHCI version = 0x%04x\n", XREAD2(sc, capa, XHCI_HCIVERSION));
  545 
  546         if (!(XREAD4(sc, oper, XHCI_PAGESIZE) & XHCI_PAGESIZE_4K)) {
  547                 device_printf(sc->sc_bus.parent, "Controller does "
  548                     "not support 4K page size.\n");
  549                 return (ENXIO);
  550         }
  551 
  552         temp = XREAD4(sc, capa, XHCI_HCSPARAMS0);
  553 
  554         DPRINTF("HCS0 = 0x%08x\n", temp);
  555 
  556         /* set up context size */
  557         if (XHCI_HCS0_CSZ(temp)) {
  558                 sc->sc_ctx_is_64_byte = 1;
  559         } else {
  560                 sc->sc_ctx_is_64_byte = 0;
  561         }
  562 
  563         /* get DMA bits */
  564         sc->sc_bus.dma_bits = (XHCI_HCS0_AC64(temp) &&
  565             xhcidma32 == 0 && dma32 == 0) ? 64 : 32;
  566 
  567         device_printf(self, "%d bytes context size, %d-bit DMA\n",
  568             sc->sc_ctx_is_64_byte ? 64 : 32, (int)sc->sc_bus.dma_bits);
  569 
  570         /* enable 64Kbyte control endpoint quirk */
  571         sc->sc_bus.control_ep_quirk = (xhcictlquirk ? 1 : 0);
  572 
  573         temp = XREAD4(sc, capa, XHCI_HCSPARAMS1);
  574 
  575         /* get number of device slots */
  576         sc->sc_noport = XHCI_HCS1_N_PORTS(temp);
  577 
  578         if (sc->sc_noport == 0) {
  579                 device_printf(sc->sc_bus.parent, "Invalid number "
  580                     "of ports: %u\n", sc->sc_noport);
  581                 return (ENXIO);
  582         }
  583 
  584         sc->sc_noslot = XHCI_HCS1_DEVSLOT_MAX(temp);
  585 
  586         DPRINTF("Max slots: %u\n", sc->sc_noslot);
  587 
  588         if (sc->sc_noslot > XHCI_MAX_DEVICES)
  589                 sc->sc_noslot = XHCI_MAX_DEVICES;
  590 
  591         temp = XREAD4(sc, capa, XHCI_HCSPARAMS2);
  592 
  593         DPRINTF("HCS2=0x%08x\n", temp);
  594 
  595         /* get isochronous scheduling threshold */
  596         sc->sc_ist = XHCI_HCS2_IST(temp);
  597 
  598         /* get number of scratchpads */
  599         sc->sc_noscratch = XHCI_HCS2_SPB_MAX(temp);
  600 
  601         if (sc->sc_noscratch > XHCI_MAX_SCRATCHPADS) {
  602                 device_printf(sc->sc_bus.parent, "XHCI request "
  603                     "too many scratchpads\n");
  604                 return (ENOMEM);
  605         }
  606 
  607         DPRINTF("Max scratch: %u\n", sc->sc_noscratch);
  608 
  609         /* get event table size */
  610         sc->sc_erst_max = 1U << XHCI_HCS2_ERST_MAX(temp);
  611         if (sc->sc_erst_max > XHCI_MAX_RSEG)
  612                 sc->sc_erst_max = XHCI_MAX_RSEG;
  613 
  614         temp = XREAD4(sc, capa, XHCI_HCSPARAMS3);
  615 
  616         /* get maximum exit latency */
  617         sc->sc_exit_lat_max = XHCI_HCS3_U1_DEL(temp) +
  618             XHCI_HCS3_U2_DEL(temp) + 250 /* us */;
  619 
  620         /* Check if we should use the default IMOD value. */
  621         if (sc->sc_imod_default == 0)
  622                 sc->sc_imod_default = XHCI_IMOD_DEFAULT;
  623 
  624         /* get all DMA memory */
  625         if (usb_bus_mem_alloc_all(&sc->sc_bus,
  626             USB_GET_DMA_TAG(self), &xhci_iterate_hw_softc)) {
  627                 return (ENOMEM);
  628         }
  629 
  630         /* set up command queue mutex and condition varible */
  631         cv_init(&sc->sc_cmd_cv, "CMDQ");
  632         sx_init(&sc->sc_cmd_sx, "CMDQ lock");
  633 
  634         sc->sc_config_msg[0].hdr.pm_callback = &xhci_configure_msg;
  635         sc->sc_config_msg[0].bus = &sc->sc_bus;
  636         sc->sc_config_msg[1].hdr.pm_callback = &xhci_configure_msg;
  637         sc->sc_config_msg[1].bus = &sc->sc_bus;
  638 
  639         return (0);
  640 }
  641 
  642 void
  643 xhci_uninit(struct xhci_softc *sc)
  644 {
  645         /*
  646          * NOTE: At this point the control transfer process is gone
  647          * and "xhci_configure_msg" is no longer called. Consequently
  648          * waiting for the configuration messages to complete is not
  649          * needed.
  650          */
  651         usb_bus_mem_free_all(&sc->sc_bus, &xhci_iterate_hw_softc);
  652 
  653         cv_destroy(&sc->sc_cmd_cv);
  654         sx_destroy(&sc->sc_cmd_sx);
  655 }
  656 
  657 static void
  658 xhci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state)
  659 {
  660         struct xhci_softc *sc = XHCI_BUS2SC(bus);
  661 
  662         switch (state) {
  663         case USB_HW_POWER_SUSPEND:
  664                 DPRINTF("Stopping the XHCI\n");
  665                 xhci_halt_controller(sc);
  666                 xhci_reset_controller(sc);
  667                 break;
  668         case USB_HW_POWER_SHUTDOWN:
  669                 DPRINTF("Stopping the XHCI\n");
  670                 xhci_halt_controller(sc);
  671                 xhci_reset_controller(sc);
  672                 break;
  673         case USB_HW_POWER_RESUME:
  674                 DPRINTF("Starting the XHCI\n");
  675                 xhci_start_controller(sc);
  676                 break;
  677         default:
  678                 break;
  679         }
  680 }
  681 
  682 static usb_error_t
  683 xhci_generic_done_sub(struct usb_xfer *xfer)
  684 {
  685         struct xhci_td *td;
  686         struct xhci_td *td_alt_next;
  687         uint32_t len;
  688         uint8_t status;
  689 
  690         td = xfer->td_transfer_cache;
  691         td_alt_next = td->alt_next;
  692 
  693         if (xfer->aframes != xfer->nframes)
  694                 usbd_xfer_set_frame_len(xfer, xfer->aframes, 0);
  695 
  696         while (1) {
  697                 usb_pc_cpu_invalidate(td->page_cache);
  698 
  699                 status = td->status;
  700                 len = td->remainder;
  701 
  702                 DPRINTFN(4, "xfer=%p[%u/%u] rem=%u/%u status=%u\n",
  703                     xfer, (unsigned)xfer->aframes,
  704                     (unsigned)xfer->nframes,
  705                     (unsigned)len, (unsigned)td->len,
  706                     (unsigned)status);
  707 
  708                 /*
  709                  * Verify the status length and
  710                  * add the length to "frlengths[]":
  711                  */
  712                 if (len > td->len) {
  713                         /* should not happen */
  714                         DPRINTF("Invalid status length, "
  715                             "0x%04x/0x%04x bytes\n", len, td->len);
  716                         status = XHCI_TRB_ERROR_LENGTH;
  717                 } else if (xfer->aframes != xfer->nframes) {
  718                         xfer->frlengths[xfer->aframes] += td->len - len;
  719                 }
  720                 /* Check for last transfer */
  721                 if (((void *)td) == xfer->td_transfer_last) {
  722                         td = NULL;
  723                         break;
  724                 }
  725                 /* Check for transfer error */
  726                 if (status != XHCI_TRB_ERROR_SHORT_PKT &&
  727                     status != XHCI_TRB_ERROR_SUCCESS) {
  728                         /* the transfer is finished */
  729                         td = NULL;
  730                         break;
  731                 }
  732                 /* Check for short transfer */
  733                 if (len > 0) {
  734                         if (xfer->flags_int.short_frames_ok || 
  735                             xfer->flags_int.isochronous_xfr ||
  736                             xfer->flags_int.control_xfr) {
  737                                 /* follow alt next */
  738                                 td = td->alt_next;
  739                         } else {
  740                                 /* the transfer is finished */
  741                                 td = NULL;
  742                         }
  743                         break;
  744                 }
  745                 td = td->obj_next;
  746 
  747                 if (td->alt_next != td_alt_next) {
  748                         /* this USB frame is complete */
  749                         break;
  750                 }
  751         }
  752 
  753         /* update transfer cache */
  754 
  755         xfer->td_transfer_cache = td;
  756 
  757         return ((status == XHCI_TRB_ERROR_STALL) ? USB_ERR_STALLED : 
  758             (status != XHCI_TRB_ERROR_SHORT_PKT && 
  759             status != XHCI_TRB_ERROR_SUCCESS) ? USB_ERR_IOERROR :
  760             USB_ERR_NORMAL_COMPLETION);
  761 }
  762 
  763 static void
  764 xhci_generic_done(struct usb_xfer *xfer)
  765 {
  766         usb_error_t err = 0;
  767 
  768         DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
  769             xfer, xfer->endpoint);
  770 
  771         /* reset scanner */
  772 
  773         xfer->td_transfer_cache = xfer->td_transfer_first;
  774 
  775         if (xfer->flags_int.control_xfr) {
  776                 if (xfer->flags_int.control_hdr)
  777                         err = xhci_generic_done_sub(xfer);
  778 
  779                 xfer->aframes = 1;
  780 
  781                 if (xfer->td_transfer_cache == NULL)
  782                         goto done;
  783         }
  784 
  785         while (xfer->aframes != xfer->nframes) {
  786                 err = xhci_generic_done_sub(xfer);
  787                 xfer->aframes++;
  788 
  789                 if (xfer->td_transfer_cache == NULL)
  790                         goto done;
  791         }
  792 
  793         if (xfer->flags_int.control_xfr &&
  794             !xfer->flags_int.control_act)
  795                 err = xhci_generic_done_sub(xfer);
  796 done:
  797         /* transfer is complete */
  798         xhci_device_done(xfer, err);
  799 }
  800 
  801 static void
  802 xhci_activate_transfer(struct usb_xfer *xfer)
  803 {
  804         struct xhci_td *td;
  805 
  806         td = xfer->td_transfer_cache;
  807 
  808         usb_pc_cpu_invalidate(td->page_cache);
  809 
  810         if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
  811                 /* activate the transfer */
  812 
  813                 td->td_trb[0].dwTrb3 |= htole32(XHCI_TRB_3_CYCLE_BIT);
  814                 usb_pc_cpu_flush(td->page_cache);
  815 
  816                 xhci_endpoint_doorbell(xfer);
  817         }
  818 }
  819 
  820 static void
  821 xhci_skip_transfer(struct usb_xfer *xfer)
  822 {
  823         struct xhci_td *td;
  824         struct xhci_td *td_last;
  825 
  826         td = xfer->td_transfer_cache;
  827         td_last = xfer->td_transfer_last;
  828 
  829         td = td->alt_next;
  830 
  831         usb_pc_cpu_invalidate(td->page_cache);
  832 
  833         if (!(td->td_trb[0].dwTrb3 & htole32(XHCI_TRB_3_CYCLE_BIT))) {
  834                 usb_pc_cpu_invalidate(td_last->page_cache);
  835 
  836                 /* copy LINK TRB to current waiting location */
  837 
  838                 td->td_trb[0].qwTrb0 = td_last->td_trb[td_last->ntrb].qwTrb0;
  839                 td->td_trb[0].dwTrb2 = td_last->td_trb[td_last->ntrb].dwTrb2;
  840                 usb_pc_cpu_flush(td->page_cache);
  841 
  842                 td->td_trb[0].dwTrb3 = td_last->td_trb[td_last->ntrb].dwTrb3;
  843                 usb_pc_cpu_flush(td->page_cache);
  844 
  845                 xhci_endpoint_doorbell(xfer);
  846         }
  847 }
  848 
  849 /*------------------------------------------------------------------------*
  850  *      xhci_check_transfer
  851  *------------------------------------------------------------------------*/
  852 static void
  853 xhci_check_transfer(struct xhci_softc *sc, struct xhci_trb *trb)
  854 {
  855         struct xhci_endpoint_ext *pepext;
  856         int64_t offset;
  857         uint64_t td_event;
  858         uint32_t temp;
  859         uint32_t remainder;
  860         uint16_t stream_id = 0;
  861         uint16_t i;
  862         uint8_t status;
  863         uint8_t halted;
  864         uint8_t epno;
  865         uint8_t index;
  866 
  867         /* decode TRB */
  868         td_event = le64toh(trb->qwTrb0);
  869         temp = le32toh(trb->dwTrb2);
  870 
  871         remainder = XHCI_TRB_2_REM_GET(temp);
  872         status = XHCI_TRB_2_ERROR_GET(temp);
  873 
  874         temp = le32toh(trb->dwTrb3);
  875         epno = XHCI_TRB_3_EP_GET(temp);
  876         index = XHCI_TRB_3_SLOT_GET(temp);
  877 
  878         /* check if error means halted */
  879         halted = (status != XHCI_TRB_ERROR_SHORT_PKT &&
  880             status != XHCI_TRB_ERROR_SUCCESS);
  881 
  882         DPRINTF("slot=%u epno=%u remainder=%u status=%u\n",
  883             index, epno, remainder, status);
  884 
  885         if (index > sc->sc_noslot) {
  886                 DPRINTF("Invalid slot.\n");
  887                 return;
  888         }
  889 
  890         if ((epno == 0) || (epno >= XHCI_MAX_ENDPOINTS)) {
  891                 DPRINTF("Invalid endpoint.\n");
  892                 return;
  893         }
  894 
  895         pepext = &sc->sc_hw.devs[index].endp[epno];
  896 
  897         /* try to find the USB transfer that generated the event */
  898         for (i = 0;; i++) {
  899                 struct usb_xfer *xfer;
  900                 struct xhci_td *td;
  901 
  902                 if (i == (XHCI_MAX_TRANSFERS - 1)) {
  903                         if (pepext->trb_ep_mode != USB_EP_MODE_STREAMS ||
  904                             stream_id == (XHCI_MAX_STREAMS - 1))
  905                                 break;
  906                         stream_id++;
  907                         i = 0;
  908                         DPRINTFN(5, "stream_id=%u\n", stream_id);
  909                 }
  910 
  911                 xfer = pepext->xfer[i + (XHCI_MAX_TRANSFERS * stream_id)];
  912                 if (xfer == NULL)
  913                         continue;
  914 
  915                 td = xfer->td_transfer_cache;
  916 
  917                 DPRINTFN(5, "Checking if 0x%016llx == (0x%016llx .. 0x%016llx)\n",
  918                         (long long)td_event,
  919                         (long long)td->td_self,
  920                         (long long)td->td_self + sizeof(td->td_trb));
  921 
  922                 /*
  923                  * NOTE: Some XHCI implementations might not trigger
  924                  * an event on the last LINK TRB so we need to
  925                  * consider both the last and second last event
  926                  * address as conditions for a successful transfer.
  927                  *
  928                  * NOTE: We assume that the XHCI will only trigger one
  929                  * event per chain of TRBs.
  930                  */
  931 
  932                 offset = td_event - td->td_self;
  933 
  934                 if (offset >= 0 &&
  935                     offset < (int64_t)sizeof(td->td_trb)) {
  936                         usb_pc_cpu_invalidate(td->page_cache);
  937 
  938                         /* compute rest of remainder, if any */
  939                         for (i = (offset / 16) + 1; i < td->ntrb; i++) {
  940                                 temp = le32toh(td->td_trb[i].dwTrb2);
  941                                 remainder += XHCI_TRB_2_BYTES_GET(temp);
  942                         }
  943 
  944                         DPRINTFN(5, "New remainder: %u\n", remainder);
  945 
  946                         /* clear isochronous transfer errors */
  947                         if (xfer->flags_int.isochronous_xfr) {
  948                                 if (halted) {
  949                                         halted = 0;
  950                                         status = XHCI_TRB_ERROR_SUCCESS;
  951                                         remainder = td->len;
  952                                 }
  953                         }
  954 
  955                         /* "td->remainder" is verified later */
  956                         td->remainder = remainder;
  957                         td->status = status;
  958 
  959                         usb_pc_cpu_flush(td->page_cache);
  960 
  961                         /*
  962                          * 1) Last transfer descriptor makes the
  963                          * transfer done
  964                          */
  965                         if (((void *)td) == xfer->td_transfer_last) {
  966                                 DPRINTF("TD is last\n");
  967                                 xhci_generic_done(xfer);
  968                                 break;
  969                         }
  970 
  971                         /*
  972                          * 2) Any kind of error makes the transfer
  973                          * done
  974                          */
  975                         if (halted) {
  976                                 DPRINTF("TD has I/O error\n");
  977                                 xhci_generic_done(xfer);
  978                                 break;
  979                         }
  980 
  981                         /*
  982                          * 3) If there is no alternate next transfer,
  983                          * a short packet also makes the transfer done
  984                          */
  985                         if (td->remainder > 0) {
  986                                 if (td->alt_next == NULL) {
  987                                         DPRINTF(
  988                                             "short TD has no alternate next\n");
  989                                         xhci_generic_done(xfer);
  990                                         break;
  991                                 }
  992                                 DPRINTF("TD has short pkt\n");
  993                                 if (xfer->flags_int.short_frames_ok ||
  994                                     xfer->flags_int.isochronous_xfr ||
  995                                     xfer->flags_int.control_xfr) {
  996                                         /* follow the alt next */
  997                                         xfer->td_transfer_cache = td->alt_next;
  998                                         xhci_activate_transfer(xfer);
  999                                         break;
 1000                                 }
 1001                                 xhci_skip_transfer(xfer);
 1002                                 xhci_generic_done(xfer);
 1003                                 break;
 1004                         }
 1005 
 1006                         /*
 1007                          * 4) Transfer complete - go to next TD
 1008                          */
 1009                         DPRINTF("Following next TD\n");
 1010                         xfer->td_transfer_cache = td->obj_next;
 1011                         xhci_activate_transfer(xfer);
 1012                         break;          /* there should only be one match */
 1013                 }
 1014         }
 1015 }
 1016 
 1017 static int
 1018 xhci_check_command(struct xhci_softc *sc, struct xhci_trb *trb)
 1019 {
 1020         if (sc->sc_cmd_addr == trb->qwTrb0) {
 1021                 DPRINTF("Received command event\n");
 1022                 sc->sc_cmd_result[0] = trb->dwTrb2;
 1023                 sc->sc_cmd_result[1] = trb->dwTrb3;
 1024                 cv_signal(&sc->sc_cmd_cv);
 1025                 return (1);     /* command match */
 1026         }
 1027         return (0);
 1028 }
 1029 
 1030 static int
 1031 xhci_interrupt_poll(struct xhci_softc *sc)
 1032 {
 1033         struct usb_page_search buf_res;
 1034         struct xhci_hw_root *phwr;
 1035         uint64_t addr;
 1036         uint32_t temp;
 1037         int retval = 0;
 1038         uint16_t i;
 1039         uint8_t event;
 1040         uint8_t j;
 1041         uint8_t k;
 1042         uint8_t t;
 1043 
 1044         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
 1045 
 1046         phwr = buf_res.buffer;
 1047 
 1048         /* Receive any events */
 1049 
 1050         usb_pc_cpu_invalidate(&sc->sc_hw.root_pc);
 1051 
 1052         i = sc->sc_event_idx;
 1053         j = sc->sc_event_ccs;
 1054         t = 2;
 1055 
 1056         while (1) {
 1057                 temp = le32toh(phwr->hwr_events[i].dwTrb3);
 1058 
 1059                 k = (temp & XHCI_TRB_3_CYCLE_BIT) ? 1 : 0;
 1060 
 1061                 if (j != k)
 1062                         break;
 1063 
 1064                 event = XHCI_TRB_3_TYPE_GET(temp);
 1065 
 1066                 DPRINTFN(10, "event[%u] = %u (0x%016llx 0x%08lx 0x%08lx)\n",
 1067                     i, event, (long long)le64toh(phwr->hwr_events[i].qwTrb0),
 1068                     (long)le32toh(phwr->hwr_events[i].dwTrb2),
 1069                     (long)le32toh(phwr->hwr_events[i].dwTrb3));
 1070 
 1071                 switch (event) {
 1072                 case XHCI_TRB_EVENT_TRANSFER:
 1073                         xhci_check_transfer(sc, &phwr->hwr_events[i]);
 1074                         break;
 1075                 case XHCI_TRB_EVENT_CMD_COMPLETE:
 1076                         retval |= xhci_check_command(sc, &phwr->hwr_events[i]);
 1077                         break;
 1078                 default:
 1079                         DPRINTF("Unhandled event = %u\n", event);
 1080                         break;
 1081                 }
 1082 
 1083                 i++;
 1084 
 1085                 if (i == XHCI_MAX_EVENTS) {
 1086                         i = 0;
 1087                         j ^= 1;
 1088 
 1089                         /* check for timeout */
 1090                         if (!--t)
 1091                                 break;
 1092                 }
 1093         }
 1094 
 1095         sc->sc_event_idx = i;
 1096         sc->sc_event_ccs = j;
 1097 
 1098         /*
 1099          * NOTE: The Event Ring Dequeue Pointer Register is 64-bit
 1100          * latched. That means to activate the register we need to
 1101          * write both the low and high double word of the 64-bit
 1102          * register.
 1103          */
 1104 
 1105         addr = buf_res.physaddr;
 1106         addr += __offsetof(struct xhci_hw_root, hwr_events[i]);
 1107 
 1108         /* try to clear busy bit */
 1109         addr |= XHCI_ERDP_LO_BUSY;
 1110 
 1111         XWRITE4(sc, runt, XHCI_ERDP_LO(0), (uint32_t)addr);
 1112         XWRITE4(sc, runt, XHCI_ERDP_HI(0), (uint32_t)(addr >> 32));
 1113 
 1114         return (retval);
 1115 }
 1116 
 1117 static usb_error_t
 1118 xhci_do_command(struct xhci_softc *sc, struct xhci_trb *trb, 
 1119     uint16_t timeout_ms)
 1120 {
 1121         struct usb_page_search buf_res;
 1122         struct xhci_hw_root *phwr;
 1123         uint64_t addr;
 1124         uint32_t temp;
 1125         uint8_t i;
 1126         uint8_t j;
 1127         uint8_t timeout = 0;
 1128         int err;
 1129 
 1130         XHCI_CMD_ASSERT_LOCKED(sc);
 1131 
 1132         /* get hardware root structure */
 1133 
 1134         usbd_get_page(&sc->sc_hw.root_pc, 0, &buf_res);
 1135 
 1136         phwr = buf_res.buffer;
 1137 
 1138         /* Queue command */
 1139 
 1140         USB_BUS_LOCK(&sc->sc_bus);
 1141 retry:
 1142         i = sc->sc_command_idx;
 1143         j = sc->sc_command_ccs;
 1144 
 1145         DPRINTFN(10, "command[%u] = %u (0x%016llx, 0x%08lx, 0x%08lx)\n",
 1146             i, XHCI_TRB_3_TYPE_GET(le32toh(trb->dwTrb3)),
 1147             (long long)le64toh(trb->qwTrb0),
 1148             (long)le32toh(trb->dwTrb2),
 1149             (long)le32toh(trb->dwTrb3));
 1150 
 1151         phwr->hwr_commands[i].qwTrb0 = trb->qwTrb0;
 1152         phwr->hwr_commands[i].dwTrb2 = trb->dwTrb2;
 1153 
 1154         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
 1155 
 1156         temp = trb->dwTrb3;
 1157 
 1158         if (j)
 1159                 temp |= htole32(XHCI_TRB_3_CYCLE_BIT);
 1160         else
 1161                 temp &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
 1162 
 1163         temp &= ~htole32(XHCI_TRB_3_TC_BIT);
 1164 
 1165         phwr->hwr_commands[i].dwTrb3 = temp;
 1166 
 1167         usb_pc_cpu_flush(&sc->sc_hw.root_pc);
 1168 
 1169         addr = buf_res.physaddr;
 1170         addr += __offsetof(struct xhci_hw_root, hwr_commands[i]);
 1171 
 1172         sc->sc_cmd_addr = htole64(addr);
 1173 
 1174         i++;
 1175 
 1176         if (i == (XHCI_MAX_COMMANDS - 1)) {
 1177                 if (j) {
 1178                         temp = htole32(XHCI_TRB_3_TC_BIT |
 1179                             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
 1180                             XHCI_TRB_3_CYCLE_BIT);
 1181                 } else {
 1182                         temp = htole32(XHCI_TRB_3_TC_BIT |
 1183                             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
 1184                 }
 1185 
 1186                 phwr->hwr_commands[i].dwTrb3 = temp;
 1187 
 1188                 usb_pc_cpu_flush(&sc->sc_hw.root_pc);
 1189 
 1190                 i = 0;
 1191                 j ^= 1;
 1192         }
 1193 
 1194         sc->sc_command_idx = i;
 1195         sc->sc_command_ccs = j;
 1196 
 1197         XWRITE4(sc, door, XHCI_DOORBELL(0), 0);
 1198 
 1199         err = cv_timedwait(&sc->sc_cmd_cv, &sc->sc_bus.bus_mtx,
 1200             USB_MS_TO_TICKS(timeout_ms));
 1201 
 1202         /*
 1203          * In some error cases event interrupts are not generated.
 1204          * Poll one time to see if the command has completed.
 1205          */
 1206         if (err != 0 && xhci_interrupt_poll(sc) != 0) {
 1207                 DPRINTF("Command was completed when polling\n");
 1208                 err = 0;
 1209         }
 1210         if (err != 0) {
 1211                 DPRINTF("Command timeout!\n");
 1212                 /*
 1213                  * After some weeks of continuous operation, it has
 1214                  * been observed that the ASMedia Technology, ASM1042
 1215                  * SuperSpeed USB Host Controller can suddenly stop
 1216                  * accepting commands via the command queue. Try to
 1217                  * first reset the command queue. If that fails do a
 1218                  * host controller reset.
 1219                  */
 1220                 if (timeout == 0 &&
 1221                     xhci_reset_command_queue_locked(sc) == 0) {
 1222                         temp = le32toh(trb->dwTrb3);
 1223 
 1224                         /*
 1225                          * Avoid infinite XHCI reset loops if the set
 1226                          * address command fails to respond due to a
 1227                          * non-enumerating device:
 1228                          */
 1229                         if (XHCI_TRB_3_TYPE_GET(temp) == XHCI_TRB_TYPE_ADDRESS_DEVICE &&
 1230                             (temp & XHCI_TRB_3_BSR_BIT) == 0) {
 1231                                 DPRINTF("Set address timeout\n");
 1232                         } else {
 1233                                 timeout = 1;
 1234                                 goto retry;
 1235                         }
 1236                 } else {
 1237                         DPRINTF("Controller reset!\n");
 1238                         usb_bus_reset_async_locked(&sc->sc_bus);
 1239                 }
 1240                 err = USB_ERR_TIMEOUT;
 1241                 trb->dwTrb2 = 0;
 1242                 trb->dwTrb3 = 0;
 1243         } else {
 1244                 temp = le32toh(sc->sc_cmd_result[0]);
 1245                 if (XHCI_TRB_2_ERROR_GET(temp) != XHCI_TRB_ERROR_SUCCESS)
 1246                         err = USB_ERR_IOERROR;
 1247 
 1248                 trb->dwTrb2 = sc->sc_cmd_result[0];
 1249                 trb->dwTrb3 = sc->sc_cmd_result[1];
 1250         }
 1251 
 1252         USB_BUS_UNLOCK(&sc->sc_bus);
 1253 
 1254         return (err);
 1255 }
 1256 
 1257 #if 0
 1258 static usb_error_t
 1259 xhci_cmd_nop(struct xhci_softc *sc)
 1260 {
 1261         struct xhci_trb trb;
 1262         uint32_t temp;
 1263 
 1264         DPRINTF("\n");
 1265 
 1266         trb.qwTrb0 = 0;
 1267         trb.dwTrb2 = 0;
 1268         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NOOP);
 1269 
 1270         trb.dwTrb3 = htole32(temp);
 1271 
 1272         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1273 }
 1274 #endif
 1275 
 1276 static usb_error_t
 1277 xhci_cmd_enable_slot(struct xhci_softc *sc, uint8_t *pslot)
 1278 {
 1279         struct xhci_trb trb;
 1280         uint32_t temp;
 1281         usb_error_t err;
 1282 
 1283         DPRINTF("\n");
 1284 
 1285         trb.qwTrb0 = 0;
 1286         trb.dwTrb2 = 0;
 1287         trb.dwTrb3 = htole32(XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ENABLE_SLOT));
 1288 
 1289         err = xhci_do_command(sc, &trb, 100 /* ms */);
 1290         if (err)
 1291                 goto done;
 1292 
 1293         temp = le32toh(trb.dwTrb3);
 1294 
 1295         *pslot = XHCI_TRB_3_SLOT_GET(temp); 
 1296 
 1297 done:
 1298         return (err);
 1299 }
 1300 
 1301 static usb_error_t
 1302 xhci_cmd_disable_slot(struct xhci_softc *sc, uint8_t slot_id)
 1303 {
 1304         struct xhci_trb trb;
 1305         uint32_t temp;
 1306 
 1307         DPRINTF("\n");
 1308 
 1309         trb.qwTrb0 = 0;
 1310         trb.dwTrb2 = 0;
 1311         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DISABLE_SLOT) |
 1312             XHCI_TRB_3_SLOT_SET(slot_id);
 1313 
 1314         trb.dwTrb3 = htole32(temp);
 1315 
 1316         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1317 }
 1318 
 1319 static usb_error_t
 1320 xhci_cmd_set_address(struct xhci_softc *sc, uint64_t input_ctx,
 1321     uint8_t bsr, uint8_t slot_id)
 1322 {
 1323         struct xhci_trb trb;
 1324         uint32_t temp;
 1325 
 1326         DPRINTF("\n");
 1327 
 1328         trb.qwTrb0 = htole64(input_ctx);
 1329         trb.dwTrb2 = 0;
 1330         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ADDRESS_DEVICE) |
 1331             XHCI_TRB_3_SLOT_SET(slot_id);
 1332 
 1333         if (bsr)
 1334                 temp |= XHCI_TRB_3_BSR_BIT;
 1335 
 1336         trb.dwTrb3 = htole32(temp);
 1337 
 1338         return (xhci_do_command(sc, &trb, 500 /* ms */));
 1339 }
 1340 
 1341 static usb_error_t
 1342 xhci_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t address)
 1343 {
 1344         struct usb_page_search buf_inp;
 1345         struct usb_page_search buf_dev;
 1346         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 1347         struct xhci_hw_dev *hdev;
 1348         struct xhci_slot_ctx *slot;
 1349         struct xhci_endpoint_ext *pepext;
 1350         uint32_t temp;
 1351         uint16_t mps;
 1352         usb_error_t err;
 1353         uint8_t index;
 1354 
 1355         /* the root HUB case is not handled here */
 1356         if (udev->parent_hub == NULL)
 1357                 return (USB_ERR_INVAL);
 1358 
 1359         index = udev->controller_slot_id;
 1360 
 1361         hdev =  &sc->sc_hw.devs[index];
 1362 
 1363         if (mtx != NULL)
 1364                 mtx_unlock(mtx);
 1365 
 1366         XHCI_CMD_LOCK(sc);
 1367 
 1368         switch (hdev->state) {
 1369         case XHCI_ST_DEFAULT:
 1370         case XHCI_ST_ENABLED:
 1371 
 1372                 hdev->state = XHCI_ST_ENABLED;
 1373 
 1374                 /* set configure mask to slot and EP0 */
 1375                 xhci_configure_mask(udev, 3, 0);
 1376 
 1377                 /* configure input slot context structure */
 1378                 err = xhci_configure_device(udev);
 1379 
 1380                 if (err != 0) {
 1381                         DPRINTF("Could not configure device\n");
 1382                         break;
 1383                 }
 1384 
 1385                 /* configure input endpoint context structure */
 1386                 switch (udev->speed) {
 1387                 case USB_SPEED_LOW:
 1388                 case USB_SPEED_FULL:
 1389                         mps = 8;
 1390                         break;
 1391                 case USB_SPEED_HIGH:
 1392                         mps = 64;
 1393                         break;
 1394                 default:
 1395                         mps = 512;
 1396                         break;
 1397                 }
 1398 
 1399                 pepext = xhci_get_endpoint_ext(udev,
 1400                     &udev->ctrl_ep_desc);
 1401 
 1402                 /* ensure the control endpoint is setup again */
 1403                 USB_BUS_LOCK(udev->bus);
 1404                 pepext->trb_halted = 1;
 1405                 pepext->trb_running = 0;
 1406                 USB_BUS_UNLOCK(udev->bus);
 1407 
 1408                 err = xhci_configure_endpoint(udev,
 1409                     &udev->ctrl_ep_desc, pepext,
 1410                     0, 1, 1, 0, mps, mps, USB_EP_MODE_DEFAULT);
 1411 
 1412                 if (err != 0) {
 1413                         DPRINTF("Could not configure default endpoint\n");
 1414                         break;
 1415                 }
 1416 
 1417                 /* execute set address command */
 1418                 usbd_get_page(&hdev->input_pc, 0, &buf_inp);
 1419 
 1420                 err = xhci_cmd_set_address(sc, buf_inp.physaddr,
 1421                     (address == 0), index);
 1422 
 1423                 if (err != 0) {
 1424                         temp = le32toh(sc->sc_cmd_result[0]);
 1425                         if (address == 0 && sc->sc_port_route != NULL &&
 1426                             XHCI_TRB_2_ERROR_GET(temp) ==
 1427                             XHCI_TRB_ERROR_PARAMETER) {
 1428                                 /* LynxPoint XHCI - ports are not switchable */
 1429                                 /* Un-route all ports from the XHCI */
 1430                                 sc->sc_port_route(sc->sc_bus.parent, 0, ~0);
 1431                         }
 1432                         DPRINTF("Could not set address "
 1433                             "for slot %u.\n", index);
 1434                         if (address != 0)
 1435                                 break;
 1436                 }
 1437 
 1438                 /* update device address to new value */
 1439 
 1440                 usbd_get_page(&hdev->device_pc, 0, &buf_dev);
 1441                 slot = XHCI_GET_CTX(sc, xhci_dev_ctx, ctx_slot,
 1442                     buf_dev.buffer);
 1443                 usb_pc_cpu_invalidate(&hdev->device_pc);
 1444 
 1445                 temp = le32toh(slot->dwSctx3);
 1446                 udev->address = XHCI_SCTX_3_DEV_ADDR_GET(temp);
 1447 
 1448                 /* update device state to new value */
 1449 
 1450                 if (address != 0)
 1451                         hdev->state = XHCI_ST_ADDRESSED;
 1452                 else
 1453                         hdev->state = XHCI_ST_DEFAULT;
 1454                 break;
 1455 
 1456         default:
 1457                 DPRINTF("Wrong state for set address.\n");
 1458                 err = USB_ERR_IOERROR;
 1459                 break;
 1460         }
 1461         XHCI_CMD_UNLOCK(sc);
 1462 
 1463         if (mtx != NULL)
 1464                 mtx_lock(mtx);
 1465 
 1466         return (err);
 1467 }
 1468 
 1469 static usb_error_t
 1470 xhci_cmd_configure_ep(struct xhci_softc *sc, uint64_t input_ctx,
 1471     uint8_t deconfigure, uint8_t slot_id)
 1472 {
 1473         struct xhci_trb trb;
 1474         uint32_t temp;
 1475 
 1476         DPRINTF("\n");
 1477 
 1478         trb.qwTrb0 = htole64(input_ctx);
 1479         trb.dwTrb2 = 0;
 1480         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_CONFIGURE_EP) |
 1481             XHCI_TRB_3_SLOT_SET(slot_id);
 1482 
 1483         if (deconfigure) {
 1484                 if (sc->sc_no_deconfigure != 0 || xhcidcepquirk != 0)
 1485                         return (0);     /* Success */
 1486                 temp |= XHCI_TRB_3_DCEP_BIT;
 1487         }
 1488 
 1489         trb.dwTrb3 = htole32(temp);
 1490 
 1491         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1492 }
 1493 
 1494 static usb_error_t
 1495 xhci_cmd_evaluate_ctx(struct xhci_softc *sc, uint64_t input_ctx,
 1496     uint8_t slot_id)
 1497 {
 1498         struct xhci_trb trb;
 1499         uint32_t temp;
 1500 
 1501         DPRINTF("\n");
 1502 
 1503         trb.qwTrb0 = htole64(input_ctx);
 1504         trb.dwTrb2 = 0;
 1505         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_EVALUATE_CTX) |
 1506             XHCI_TRB_3_SLOT_SET(slot_id);
 1507         trb.dwTrb3 = htole32(temp);
 1508 
 1509         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1510 }
 1511 
 1512 static usb_error_t
 1513 xhci_cmd_reset_ep(struct xhci_softc *sc, uint8_t preserve,
 1514     uint8_t ep_id, uint8_t slot_id)
 1515 {
 1516         struct xhci_trb trb;
 1517         uint32_t temp;
 1518 
 1519         DPRINTF("\n");
 1520 
 1521         trb.qwTrb0 = 0;
 1522         trb.dwTrb2 = 0;
 1523         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_EP) |
 1524             XHCI_TRB_3_SLOT_SET(slot_id) |
 1525             XHCI_TRB_3_EP_SET(ep_id);
 1526 
 1527         if (preserve)
 1528                 temp |= XHCI_TRB_3_PRSV_BIT;
 1529 
 1530         trb.dwTrb3 = htole32(temp);
 1531 
 1532         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1533 }
 1534 
 1535 static usb_error_t
 1536 xhci_cmd_set_tr_dequeue_ptr(struct xhci_softc *sc, uint64_t dequeue_ptr,
 1537     uint16_t stream_id, uint8_t ep_id, uint8_t slot_id)
 1538 {
 1539         struct xhci_trb trb;
 1540         uint32_t temp;
 1541 
 1542         DPRINTF("\n");
 1543 
 1544         trb.qwTrb0 = htole64(dequeue_ptr);
 1545 
 1546         temp = XHCI_TRB_2_STREAM_SET(stream_id);
 1547         trb.dwTrb2 = htole32(temp);
 1548 
 1549         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SET_TR_DEQUEUE) |
 1550             XHCI_TRB_3_SLOT_SET(slot_id) |
 1551             XHCI_TRB_3_EP_SET(ep_id);
 1552         trb.dwTrb3 = htole32(temp);
 1553 
 1554         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1555 }
 1556 
 1557 static usb_error_t
 1558 xhci_cmd_stop_ep(struct xhci_softc *sc, uint8_t suspend,
 1559     uint8_t ep_id, uint8_t slot_id)
 1560 {
 1561         struct xhci_trb trb;
 1562         uint32_t temp;
 1563 
 1564         DPRINTF("\n");
 1565 
 1566         trb.qwTrb0 = 0;
 1567         trb.dwTrb2 = 0;
 1568         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STOP_EP) |
 1569             XHCI_TRB_3_SLOT_SET(slot_id) |
 1570             XHCI_TRB_3_EP_SET(ep_id);
 1571 
 1572         if (suspend)
 1573                 temp |= XHCI_TRB_3_SUSP_EP_BIT;
 1574 
 1575         trb.dwTrb3 = htole32(temp);
 1576 
 1577         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1578 }
 1579 
 1580 static usb_error_t
 1581 xhci_cmd_reset_dev(struct xhci_softc *sc, uint8_t slot_id)
 1582 {
 1583         struct xhci_trb trb;
 1584         uint32_t temp;
 1585 
 1586         DPRINTF("\n");
 1587 
 1588         trb.qwTrb0 = 0;
 1589         trb.dwTrb2 = 0;
 1590         temp = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_RESET_DEVICE) |
 1591             XHCI_TRB_3_SLOT_SET(slot_id);
 1592 
 1593         trb.dwTrb3 = htole32(temp);
 1594 
 1595         return (xhci_do_command(sc, &trb, 100 /* ms */));
 1596 }
 1597 
 1598 /*------------------------------------------------------------------------*
 1599  *      xhci_interrupt - XHCI interrupt handler
 1600  *------------------------------------------------------------------------*/
 1601 void
 1602 xhci_interrupt(struct xhci_softc *sc)
 1603 {
 1604         uint32_t status;
 1605         uint32_t temp;
 1606 
 1607         USB_BUS_LOCK(&sc->sc_bus);
 1608 
 1609         status = XREAD4(sc, oper, XHCI_USBSTS);
 1610 
 1611         /* acknowledge interrupts, if any */
 1612         if (status != 0) {
 1613                 XWRITE4(sc, oper, XHCI_USBSTS, status);
 1614                 DPRINTFN(16, "real interrupt (status=0x%08x)\n", status);
 1615         }
 1616 
 1617         temp = XREAD4(sc, runt, XHCI_IMAN(0));
 1618 
 1619         /* force clearing of pending interrupts */
 1620         if (temp & XHCI_IMAN_INTR_PEND)
 1621                 XWRITE4(sc, runt, XHCI_IMAN(0), temp);
 1622 
 1623         /* check for event(s) */
 1624         xhci_interrupt_poll(sc);
 1625 
 1626         if (status & (XHCI_STS_PCD | XHCI_STS_HCH |
 1627             XHCI_STS_HSE | XHCI_STS_HCE)) {
 1628                 if (status & XHCI_STS_PCD) {
 1629                         xhci_root_intr(sc);
 1630                 }
 1631 
 1632                 if (status & XHCI_STS_HCH) {
 1633                         printf("%s: host controller halted\n",
 1634                             __FUNCTION__);
 1635                 }
 1636 
 1637                 if (status & XHCI_STS_HSE) {
 1638                         printf("%s: host system error\n",
 1639                             __FUNCTION__);
 1640                 }
 1641 
 1642                 if (status & XHCI_STS_HCE) {
 1643                         printf("%s: host controller error\n",
 1644                            __FUNCTION__);
 1645                 }
 1646         }
 1647         USB_BUS_UNLOCK(&sc->sc_bus);
 1648 }
 1649 
 1650 /*------------------------------------------------------------------------*
 1651  *      xhci_timeout - XHCI timeout handler
 1652  *------------------------------------------------------------------------*/
 1653 static void
 1654 xhci_timeout(void *arg)
 1655 {
 1656         struct usb_xfer *xfer = arg;
 1657 
 1658         DPRINTF("xfer=%p\n", xfer);
 1659 
 1660         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
 1661 
 1662         /* transfer is transferred */
 1663         xhci_device_done(xfer, USB_ERR_TIMEOUT);
 1664 }
 1665 
 1666 static void
 1667 xhci_do_poll(struct usb_bus *bus)
 1668 {
 1669         struct xhci_softc *sc = XHCI_BUS2SC(bus);
 1670 
 1671         USB_BUS_LOCK(&sc->sc_bus);
 1672         xhci_interrupt_poll(sc);
 1673         USB_BUS_UNLOCK(&sc->sc_bus);
 1674 }
 1675 
 1676 static void
 1677 xhci_setup_generic_chain_sub(struct xhci_std_temp *temp)
 1678 {
 1679         struct usb_page_search buf_res;
 1680         struct xhci_td *td;
 1681         struct xhci_td *td_next;
 1682         struct xhci_td *td_alt_next;
 1683         struct xhci_td *td_first;
 1684         uint32_t buf_offset;
 1685         uint32_t average;
 1686         uint32_t len_old;
 1687         uint32_t npkt_off;
 1688         uint32_t dword;
 1689         uint8_t shortpkt_old;
 1690         uint8_t precompute;
 1691         uint8_t x;
 1692 
 1693         td_alt_next = NULL;
 1694         buf_offset = 0;
 1695         shortpkt_old = temp->shortpkt;
 1696         len_old = temp->len;
 1697         npkt_off = 0;
 1698         precompute = 1;
 1699 
 1700 restart:
 1701 
 1702         td = temp->td;
 1703         td_next = td_first = temp->td_next;
 1704 
 1705         while (1) {
 1706                 if (temp->len == 0) {
 1707                         if (temp->shortpkt)
 1708                                 break;
 1709 
 1710                         /* send a Zero Length Packet, ZLP, last */
 1711 
 1712                         temp->shortpkt = 1;
 1713                         average = 0;
 1714 
 1715                 } else {
 1716                         average = temp->average;
 1717 
 1718                         if (temp->len < average) {
 1719                                 if (temp->len % temp->max_packet_size) {
 1720                                         temp->shortpkt = 1;
 1721                                 }
 1722                                 average = temp->len;
 1723                         }
 1724                 }
 1725 
 1726                 if (td_next == NULL)
 1727                         panic("%s: out of XHCI transfer descriptors!", __FUNCTION__);
 1728 
 1729                 /* get next TD */
 1730 
 1731                 td = td_next;
 1732                 td_next = td->obj_next;
 1733 
 1734                 /* check if we are pre-computing */
 1735 
 1736                 if (precompute) {
 1737                         /* update remaining length */
 1738 
 1739                         temp->len -= average;
 1740 
 1741                         continue;
 1742                 }
 1743                 /* fill out current TD */
 1744 
 1745                 td->len = average;
 1746                 td->remainder = 0;
 1747                 td->status = 0;
 1748 
 1749                 /* update remaining length */
 1750 
 1751                 temp->len -= average;
 1752 
 1753                 /* reset TRB index */
 1754 
 1755                 x = 0;
 1756 
 1757                 if (temp->trb_type == XHCI_TRB_TYPE_SETUP_STAGE) {
 1758                         /* immediate data */
 1759 
 1760                         if (average > 8)
 1761                                 average = 8;
 1762 
 1763                         td->td_trb[0].qwTrb0 = 0;
 1764 
 1765                         usbd_copy_out(temp->pc, temp->offset + buf_offset, 
 1766                            (uint8_t *)(uintptr_t)&td->td_trb[0].qwTrb0,
 1767                            average);
 1768 
 1769                         dword = XHCI_TRB_2_BYTES_SET(8) |
 1770                             XHCI_TRB_2_TDSZ_SET(0) |
 1771                             XHCI_TRB_2_IRQ_SET(0);
 1772 
 1773                         td->td_trb[0].dwTrb2 = htole32(dword);
 1774 
 1775                         dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_SETUP_STAGE) |
 1776                           XHCI_TRB_3_IDT_BIT | XHCI_TRB_3_CYCLE_BIT;
 1777 
 1778                         /* check wLength */
 1779                         if (td->td_trb[0].qwTrb0 &
 1780                            htole64(XHCI_TRB_0_WLENGTH_MASK)) {
 1781                                 if (td->td_trb[0].qwTrb0 &
 1782                                     htole64(XHCI_TRB_0_DIR_IN_MASK))
 1783                                         dword |= XHCI_TRB_3_TRT_IN;
 1784                                 else
 1785                                         dword |= XHCI_TRB_3_TRT_OUT;
 1786                         }
 1787 
 1788                         td->td_trb[0].dwTrb3 = htole32(dword);
 1789 #ifdef USB_DEBUG
 1790                         xhci_dump_trb(&td->td_trb[x]);
 1791 #endif
 1792                         x++;
 1793 
 1794                 } else do {
 1795                         uint32_t npkt;
 1796 
 1797                         /* fill out buffer pointers */
 1798 
 1799                         if (average == 0) {
 1800                                 memset(&buf_res, 0, sizeof(buf_res));
 1801                         } else {
 1802                                 usbd_get_page(temp->pc, temp->offset +
 1803                                     buf_offset, &buf_res);
 1804 
 1805                                 /* get length to end of page */
 1806                                 if (buf_res.length > average)
 1807                                         buf_res.length = average;
 1808 
 1809                                 /* check for maximum length */
 1810                                 if (buf_res.length > XHCI_TD_PAGE_SIZE)
 1811                                         buf_res.length = XHCI_TD_PAGE_SIZE;
 1812 
 1813                                 npkt_off += buf_res.length;
 1814                         }
 1815 
 1816                         /* set up npkt */
 1817                         npkt = howmany(len_old - npkt_off,
 1818                                        temp->max_packet_size);
 1819 
 1820                         if (npkt == 0)
 1821                                 npkt = 1;
 1822                         else if (npkt > 31)
 1823                                 npkt = 31;
 1824 
 1825                         /* fill out TRB's */
 1826                         td->td_trb[x].qwTrb0 =
 1827                             htole64((uint64_t)buf_res.physaddr);
 1828 
 1829                         dword =
 1830                           XHCI_TRB_2_BYTES_SET(buf_res.length) |
 1831                           XHCI_TRB_2_TDSZ_SET(npkt) | 
 1832                           XHCI_TRB_2_IRQ_SET(0);
 1833 
 1834                         td->td_trb[x].dwTrb2 = htole32(dword);
 1835 
 1836                         switch (temp->trb_type) {
 1837                         case XHCI_TRB_TYPE_ISOCH:
 1838                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
 1839                                     XHCI_TRB_3_TBC_SET(temp->tbc) |
 1840                                     XHCI_TRB_3_TLBPC_SET(temp->tlbpc);
 1841                                 if (td != td_first) {
 1842                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
 1843                                 } else if (temp->do_isoc_sync != 0) {
 1844                                         temp->do_isoc_sync = 0;
 1845                                         /* wait until "isoc_frame" */
 1846                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
 1847                                             XHCI_TRB_3_FRID_SET(temp->isoc_frame / 8);
 1848                                 } else {
 1849                                         /* start data transfer at next interval */
 1850                                         dword |= XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_ISOCH) |
 1851                                             XHCI_TRB_3_ISO_SIA_BIT;
 1852                                 }
 1853                                 if (temp->direction == UE_DIR_IN)
 1854                                         dword |= XHCI_TRB_3_ISP_BIT;
 1855                                 break;
 1856                         case XHCI_TRB_TYPE_DATA_STAGE:
 1857                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
 1858                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_DATA_STAGE);
 1859                                 if (temp->direction == UE_DIR_IN)
 1860                                         dword |= XHCI_TRB_3_DIR_IN | XHCI_TRB_3_ISP_BIT;
 1861                                 /*
 1862                                  * Section 3.2.9 in the XHCI
 1863                                  * specification about control
 1864                                  * transfers says that we should use a
 1865                                  * normal-TRB if there are more TRBs
 1866                                  * extending the data-stage
 1867                                  * TRB. Update the "trb_type".
 1868                                  */
 1869                                 temp->trb_type = XHCI_TRB_TYPE_NORMAL;
 1870                                 break;
 1871                         case XHCI_TRB_TYPE_STATUS_STAGE:
 1872                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
 1873                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_STATUS_STAGE);
 1874                                 if (temp->direction == UE_DIR_IN)
 1875                                         dword |= XHCI_TRB_3_DIR_IN;
 1876                                 break;
 1877                         default:        /* XHCI_TRB_TYPE_NORMAL */
 1878                                 dword = XHCI_TRB_3_CHAIN_BIT | XHCI_TRB_3_CYCLE_BIT |
 1879                                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_NORMAL);
 1880                                 if (temp->direction == UE_DIR_IN)
 1881                                         dword |= XHCI_TRB_3_ISP_BIT;
 1882                                 break;
 1883                         }
 1884                         td->td_trb[x].dwTrb3 = htole32(dword);
 1885 
 1886                         average -= buf_res.length;
 1887                         buf_offset += buf_res.length;
 1888 #ifdef USB_DEBUG
 1889                         xhci_dump_trb(&td->td_trb[x]);
 1890 #endif
 1891                         x++;
 1892 
 1893                 } while (average != 0);
 1894 
 1895                 td->td_trb[x-1].dwTrb3 |= htole32(XHCI_TRB_3_IOC_BIT);
 1896 
 1897                 /* store number of data TRB's */
 1898 
 1899                 td->ntrb = x;
 1900 
 1901                 DPRINTF("NTRB=%u\n", x);
 1902 
 1903                 /* fill out link TRB */
 1904 
 1905                 if (td_next != NULL) {
 1906                         /* link the current TD with the next one */
 1907                         td->td_trb[x].qwTrb0 = htole64((uint64_t)td_next->td_self);
 1908                         DPRINTF("LINK=0x%08llx\n", (long long)td_next->td_self);
 1909                 } else {
 1910                         /* this field will get updated later */
 1911                         DPRINTF("NOLINK\n");
 1912                 }
 1913 
 1914                 dword = XHCI_TRB_2_IRQ_SET(0);
 1915 
 1916                 td->td_trb[x].dwTrb2 = htole32(dword);
 1917 
 1918                 dword = XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK) |
 1919                     XHCI_TRB_3_CYCLE_BIT | XHCI_TRB_3_IOC_BIT |
 1920                     /*
 1921                      * CHAIN-BIT: Ensure that a multi-TRB IN-endpoint
 1922                      * frame only receives a single short packet event
 1923                      * by setting the CHAIN bit in the LINK field. In
 1924                      * addition some XHCI controllers have problems
 1925                      * sending a ZLP unless the CHAIN-BIT is set in
 1926                      * the LINK TRB.
 1927                      */
 1928                     XHCI_TRB_3_CHAIN_BIT;
 1929 
 1930                 td->td_trb[x].dwTrb3 = htole32(dword);
 1931 
 1932                 td->alt_next = td_alt_next;
 1933 #ifdef USB_DEBUG
 1934                 xhci_dump_trb(&td->td_trb[x]);
 1935 #endif
 1936                 usb_pc_cpu_flush(td->page_cache);
 1937         }
 1938 
 1939         if (precompute) {
 1940                 precompute = 0;
 1941 
 1942                 /* set up alt next pointer, if any */
 1943                 if (temp->last_frame) {
 1944                         td_alt_next = NULL;
 1945                 } else {
 1946                         /* we use this field internally */
 1947                         td_alt_next = td_next;
 1948                 }
 1949 
 1950                 /* restore */
 1951                 temp->shortpkt = shortpkt_old;
 1952                 temp->len = len_old;
 1953                 goto restart;
 1954         }
 1955 
 1956         /*
 1957          * Remove cycle bit from the first TRB if we are
 1958          * stepping them:
 1959          */
 1960         if (temp->step_td != 0) {
 1961                 td_first->td_trb[0].dwTrb3 &= ~htole32(XHCI_TRB_3_CYCLE_BIT);
 1962                 usb_pc_cpu_flush(td_first->page_cache);
 1963         }
 1964 
 1965         /* clear TD SIZE to zero, hence this is the last TRB */
 1966         /* remove chain bit because this is the last data TRB in the chain */
 1967         td->td_trb[td->ntrb - 1].dwTrb2 &= ~htole32(XHCI_TRB_2_TDSZ_SET(31));
 1968         td->td_trb[td->ntrb - 1].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
 1969         /* remove CHAIN-BIT from last LINK TRB */
 1970         td->td_trb[td->ntrb].dwTrb3 &= ~htole32(XHCI_TRB_3_CHAIN_BIT);
 1971 
 1972         usb_pc_cpu_flush(td->page_cache);
 1973 
 1974         temp->td = td;
 1975         temp->td_next = td_next;
 1976 }
 1977 
 1978 static void
 1979 xhci_setup_generic_chain(struct usb_xfer *xfer)
 1980 {
 1981         struct xhci_std_temp temp;
 1982         struct xhci_td *td;
 1983         uint32_t x;
 1984         uint32_t y;
 1985         uint8_t mult;
 1986 
 1987         temp.do_isoc_sync = 0;
 1988         temp.step_td = 0;
 1989         temp.tbc = 0;
 1990         temp.tlbpc = 0;
 1991         temp.average = xfer->max_hc_frame_size;
 1992         temp.max_packet_size = xfer->max_packet_size;
 1993         temp.sc = XHCI_BUS2SC(xfer->xroot->bus);
 1994         temp.pc = NULL;
 1995         temp.last_frame = 0;
 1996         temp.offset = 0;
 1997         temp.multishort = xfer->flags_int.isochronous_xfr ||
 1998             xfer->flags_int.control_xfr ||
 1999             xfer->flags_int.short_frames_ok;
 2000 
 2001         /* toggle the DMA set we are using */
 2002         xfer->flags_int.curr_dma_set ^= 1;
 2003 
 2004         /* get next DMA set */
 2005         td = xfer->td_start[xfer->flags_int.curr_dma_set];
 2006 
 2007         temp.td = NULL;
 2008         temp.td_next = td;
 2009 
 2010         xfer->td_transfer_first = td;
 2011         xfer->td_transfer_cache = td;
 2012 
 2013         if (xfer->flags_int.isochronous_xfr) {
 2014                 uint8_t shift;
 2015 
 2016                 /* compute multiplier for ISOCHRONOUS transfers */
 2017                 mult = xfer->endpoint->ecomp ?
 2018                     UE_GET_SS_ISO_MULT(xfer->endpoint->ecomp->bmAttributes)
 2019                     : 0;
 2020                 /* check for USB 2.0 multiplier */
 2021                 if (mult == 0) {
 2022                         mult = (xfer->endpoint->edesc->
 2023                             wMaxPacketSize[1] >> 3) & 3;
 2024                 }
 2025                 /* range check */
 2026                 if (mult > 2)
 2027                         mult = 3;
 2028                 else
 2029                         mult++;
 2030 
 2031                 x = XREAD4(temp.sc, runt, XHCI_MFINDEX);
 2032 
 2033                 DPRINTF("MFINDEX=0x%08x IST=0x%x\n", x, temp.sc->sc_ist);
 2034 
 2035                 switch (usbd_get_speed(xfer->xroot->udev)) {
 2036                 case USB_SPEED_FULL:
 2037                         shift = 3;
 2038                         temp.isoc_delta = 8;    /* 1ms */
 2039                         break;
 2040                 default:
 2041                         shift = usbd_xfer_get_fps_shift(xfer);
 2042                         temp.isoc_delta = 1U << shift;
 2043                         break;
 2044                 }
 2045 
 2046                 /* Compute isochronous scheduling threshold. */
 2047                 if (temp.sc->sc_ist & 8)
 2048                         y = (temp.sc->sc_ist & 7) << 3;
 2049                 else
 2050                         y = (temp.sc->sc_ist & 7);
 2051 
 2052                 /* Range check the IST. */
 2053                 if (y < 8) {
 2054                         y = 0;
 2055                 } else if (y > 15) {
 2056                         DPRINTFN(3, "IST(%d) is too big!\n", temp.sc->sc_ist);
 2057                         /*
 2058                          * The USB stack minimum isochronous transfer
 2059                          * size is typically 2x2 ms of payload. If the
 2060                          * IST makes is above 15 microframes, we have
 2061                          * an effective scheduling delay of more than
 2062                          * or equal to 2 milliseconds, which is too
 2063                          * much.
 2064                          */
 2065                         y = 7;
 2066                 } else {
 2067                         /*
 2068                          * Subtract one millisecond, because the
 2069                          * generic code adds that to the latency.
 2070                          */
 2071                         y -= 8;
 2072                 }
 2073 
 2074                 if (usbd_xfer_get_isochronous_start_frame(
 2075                     xfer, x, y, 8, XHCI_MFINDEX_GET(-1), &temp.isoc_frame)) {
 2076                         /* Start isochronous transfer at specified time. */
 2077                         temp.do_isoc_sync = 1;
 2078 
 2079                         DPRINTFN(3, "start next=%d\n", temp.isoc_frame);
 2080                 }
 2081 
 2082                 x = 0;
 2083                 temp.trb_type = XHCI_TRB_TYPE_ISOCH;
 2084 
 2085         } else if (xfer->flags_int.control_xfr) {
 2086                 /* check if we should prepend a setup message */
 2087 
 2088                 if (xfer->flags_int.control_hdr) {
 2089                         temp.len = xfer->frlengths[0];
 2090                         temp.pc = xfer->frbuffers + 0;
 2091                         temp.shortpkt = temp.len ? 1 : 0;
 2092                         temp.trb_type = XHCI_TRB_TYPE_SETUP_STAGE;
 2093                         temp.direction = 0;
 2094 
 2095                         /* check for last frame */
 2096                         if (xfer->nframes == 1) {
 2097                                 /* no STATUS stage yet, SETUP is last */
 2098                                 if (xfer->flags_int.control_act)
 2099                                         temp.last_frame = 1;
 2100                         }
 2101 
 2102                         xhci_setup_generic_chain_sub(&temp);
 2103                 }
 2104                 x = 1;
 2105                 mult = 1;
 2106                 temp.isoc_delta = 0;
 2107                 temp.isoc_frame = 0;
 2108                 temp.trb_type = xfer->flags_int.control_did_data ?
 2109                     XHCI_TRB_TYPE_NORMAL : XHCI_TRB_TYPE_DATA_STAGE;
 2110         } else {
 2111                 x = 0;
 2112                 mult = 1;
 2113                 temp.isoc_delta = 0;
 2114                 temp.isoc_frame = 0;
 2115                 temp.trb_type = XHCI_TRB_TYPE_NORMAL;
 2116         }
 2117 
 2118         if (x != xfer->nframes) {
 2119                 /* set up page_cache pointer */
 2120                 temp.pc = xfer->frbuffers + x;
 2121                 /* set endpoint direction */
 2122                 temp.direction = UE_GET_DIR(xfer->endpointno);
 2123         }
 2124 
 2125         while (x != xfer->nframes) {
 2126                 /* DATA0 / DATA1 message */
 2127 
 2128                 temp.len = xfer->frlengths[x];
 2129                 temp.step_td = ((xfer->endpointno & UE_DIR_IN) &&
 2130                     x != 0 && temp.multishort == 0);
 2131 
 2132                 x++;
 2133 
 2134                 if (x == xfer->nframes) {
 2135                         if (xfer->flags_int.control_xfr) {
 2136                                 /* no STATUS stage yet, DATA is last */
 2137                                 if (xfer->flags_int.control_act)
 2138                                         temp.last_frame = 1;
 2139                         } else {
 2140                                 temp.last_frame = 1;
 2141                         }
 2142                 }
 2143                 if (temp.len == 0) {
 2144                         /* make sure that we send an USB packet */
 2145 
 2146                         temp.shortpkt = 0;
 2147 
 2148                         temp.tbc = 0;
 2149                         temp.tlbpc = mult - 1;
 2150 
 2151                 } else if (xfer->flags_int.isochronous_xfr) {
 2152                         uint8_t tdpc;
 2153 
 2154                         /*
 2155                          * Isochronous transfers don't have short
 2156                          * packet termination:
 2157                          */
 2158 
 2159                         temp.shortpkt = 1;
 2160 
 2161                         /* isochronous transfers have a transfer limit */
 2162 
 2163                         if (temp.len > xfer->max_frame_size)
 2164                                 temp.len = xfer->max_frame_size;
 2165 
 2166                         /* compute TD packet count */
 2167                         tdpc = howmany(temp.len, xfer->max_packet_size);
 2168 
 2169                         temp.tbc = howmany(tdpc, mult) - 1;
 2170                         temp.tlbpc = (tdpc % mult);
 2171 
 2172                         if (temp.tlbpc == 0)
 2173                                 temp.tlbpc = mult - 1;
 2174                         else
 2175                                 temp.tlbpc--;
 2176                 } else {
 2177                         /* regular data transfer */
 2178 
 2179                         temp.shortpkt = xfer->flags.force_short_xfer ? 0 : 1;
 2180                 }
 2181 
 2182                 xhci_setup_generic_chain_sub(&temp);
 2183 
 2184                 if (xfer->flags_int.isochronous_xfr) {
 2185                         temp.offset += xfer->frlengths[x - 1];
 2186                         temp.isoc_frame += temp.isoc_delta;
 2187                 } else {
 2188                         /* get next Page Cache pointer */
 2189                         temp.pc = xfer->frbuffers + x;
 2190                 }
 2191         }
 2192 
 2193         /* check if we should append a status stage */
 2194 
 2195         if (xfer->flags_int.control_xfr &&
 2196             !xfer->flags_int.control_act) {
 2197                 /*
 2198                  * Send a DATA1 message and invert the current
 2199                  * endpoint direction.
 2200                  */
 2201                 if (xhcictlstep || temp.sc->sc_ctlstep) {
 2202                         /*
 2203                          * Some XHCI controllers will not delay the
 2204                          * status stage until the next SOF. Force this
 2205                          * behaviour to avoid failed control
 2206                          * transfers.
 2207                          */
 2208                         temp.step_td = (xfer->nframes != 0);
 2209                 } else {
 2210                         temp.step_td = 0;
 2211                 }
 2212                 temp.direction = UE_GET_DIR(xfer->endpointno) ^ UE_DIR_IN;
 2213                 temp.len = 0;
 2214                 temp.pc = NULL;
 2215                 temp.shortpkt = 0;
 2216                 temp.last_frame = 1;
 2217                 temp.trb_type = XHCI_TRB_TYPE_STATUS_STAGE;
 2218 
 2219                 xhci_setup_generic_chain_sub(&temp);
 2220         }
 2221 
 2222         td = temp.td;
 2223 
 2224         /* must have at least one frame! */
 2225 
 2226         xfer->td_transfer_last = td;
 2227 
 2228         DPRINTF("first=%p last=%p\n", xfer->td_transfer_first, td);
 2229 }
 2230 
 2231 static void
 2232 xhci_set_slot_pointer(struct xhci_softc *sc, uint8_t index, uint64_t dev_addr)
 2233 {
 2234         struct usb_page_search buf_res;
 2235         struct xhci_dev_ctx_addr *pdctxa;
 2236 
 2237         usbd_get_page(&sc->sc_hw.ctx_pc, 0, &buf_res);
 2238 
 2239         pdctxa = buf_res.buffer;
 2240 
 2241         DPRINTF("addr[%u]=0x%016llx\n", index, (long long)dev_addr);
 2242 
 2243         pdctxa->qwBaaDevCtxAddr[index] = htole64(dev_addr);
 2244 
 2245         usb_pc_cpu_flush(&sc->sc_hw.ctx_pc);
 2246 }
 2247 
 2248 static usb_error_t
 2249 xhci_configure_mask(struct usb_device *udev, uint32_t mask, uint8_t drop)
 2250 {
 2251         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2252         struct usb_page_search buf_inp;
 2253         struct xhci_input_ctx *input;
 2254         struct xhci_slot_ctx *slot;
 2255         uint32_t temp;
 2256         uint8_t index;
 2257         uint8_t x;
 2258 
 2259         index = udev->controller_slot_id;
 2260 
 2261         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
 2262 
 2263         input = XHCI_GET_CTX(sc, xhci_input_dev_ctx, ctx_input,
 2264             buf_inp.buffer);
 2265         slot = XHCI_GET_CTX(sc, xhci_input_dev_ctx, ctx_slot, buf_inp.buffer);
 2266 
 2267         if (drop) {
 2268                 mask &= XHCI_INCTX_NON_CTRL_MASK;
 2269                 input->dwInCtx0 = htole32(mask);
 2270                 input->dwInCtx1 = htole32(0);
 2271         } else {
 2272                 /*
 2273                  * Some hardware requires that we drop the endpoint
 2274                  * context before adding it again:
 2275                  */
 2276                 input->dwInCtx0 = htole32(mask & XHCI_INCTX_NON_CTRL_MASK);
 2277 
 2278                 /* Add new endpoint context */
 2279                 input->dwInCtx1 = htole32(mask);
 2280 
 2281                 /* find most significant set bit */
 2282                 for (x = 31; x != 1; x--) {
 2283                         if (mask & (1 << x))
 2284                                 break;
 2285                 }
 2286 
 2287                 /* adjust */
 2288                 x--;
 2289 
 2290                 /* figure out the maximum number of contexts */
 2291                 if (x > sc->sc_hw.devs[index].context_num)
 2292                         sc->sc_hw.devs[index].context_num = x;
 2293                 else
 2294                         x = sc->sc_hw.devs[index].context_num;
 2295 
 2296                 /* update number of contexts */
 2297                 temp = le32toh(slot->dwSctx0);
 2298                 temp &= ~XHCI_SCTX_0_CTX_NUM_SET(31);
 2299                 temp |= XHCI_SCTX_0_CTX_NUM_SET(x + 1);
 2300                 slot->dwSctx0 = htole32(temp);
 2301         }
 2302         usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
 2303         return (0);
 2304 }
 2305 
 2306 static usb_error_t
 2307 xhci_configure_endpoint(struct usb_device *udev,
 2308     struct usb_endpoint_descriptor *edesc, struct xhci_endpoint_ext *pepext,
 2309     uint16_t interval, uint8_t max_packet_count,
 2310     uint8_t mult, uint8_t fps_shift, uint16_t max_packet_size,
 2311     uint16_t max_frame_size, uint8_t ep_mode)
 2312 {
 2313         struct usb_page_search buf_inp;
 2314         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2315         struct xhci_endp_ctx *endp;
 2316         uint64_t ring_addr = pepext->physaddr;
 2317         uint32_t temp;
 2318         uint8_t index;
 2319         uint8_t epno;
 2320         uint8_t type;
 2321 
 2322         index = udev->controller_slot_id;
 2323 
 2324         usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
 2325 
 2326         epno = edesc->bEndpointAddress;
 2327         type = edesc->bmAttributes & UE_XFERTYPE;
 2328 
 2329         if (type == UE_CONTROL)
 2330                 epno |= UE_DIR_IN;
 2331 
 2332         epno = XHCI_EPNO2EPID(epno);
 2333 
 2334         if (epno == 0)
 2335                 return (USB_ERR_NO_PIPE);               /* invalid */
 2336 
 2337         if (max_packet_count == 0)
 2338                 return (USB_ERR_BAD_BUFSIZE);
 2339 
 2340         max_packet_count--;
 2341 
 2342         if (mult == 0)
 2343                 return (USB_ERR_BAD_BUFSIZE);
 2344 
 2345         endp = XHCI_GET_CTX(sc, xhci_input_dev_ctx, ctx_ep[epno - 1],
 2346             buf_inp.buffer);
 2347 
 2348         /* store endpoint mode */
 2349         pepext->trb_ep_mode = ep_mode;
 2350         /* store bMaxPacketSize for control endpoints */
 2351         pepext->trb_ep_maxp = edesc->wMaxPacketSize[0];
 2352         usb_pc_cpu_flush(pepext->page_cache);
 2353 
 2354         if (ep_mode == USB_EP_MODE_STREAMS) {
 2355                 temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
 2356                     XHCI_EPCTX_0_MAXP_STREAMS_SET(XHCI_MAX_STREAMS_LOG - 1) |
 2357                     XHCI_EPCTX_0_LSA_SET(1);
 2358 
 2359                 ring_addr += sizeof(struct xhci_trb) *
 2360                     XHCI_MAX_TRANSFERS * XHCI_MAX_STREAMS;
 2361         } else {
 2362                 temp = XHCI_EPCTX_0_EPSTATE_SET(0) |
 2363                     XHCI_EPCTX_0_MAXP_STREAMS_SET(0) |
 2364                     XHCI_EPCTX_0_LSA_SET(0);
 2365 
 2366                 ring_addr |= XHCI_EPCTX_2_DCS_SET(1);
 2367         }
 2368 
 2369         switch (udev->speed) {
 2370         case USB_SPEED_FULL:
 2371         case USB_SPEED_LOW:
 2372                 /* 1ms -> 125us */
 2373                 fps_shift += 3;
 2374                 break;
 2375         default:
 2376                 break;
 2377         }
 2378 
 2379         switch (type) {
 2380         case UE_INTERRUPT:
 2381                 if (fps_shift > 3)
 2382                         fps_shift--;
 2383                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
 2384                 break;
 2385         case UE_ISOCHRONOUS:
 2386                 temp |= XHCI_EPCTX_0_IVAL_SET(fps_shift);
 2387 
 2388                 switch (udev->speed) {
 2389                 case USB_SPEED_SUPER:
 2390                         if (mult > 3)
 2391                                 mult = 3;
 2392                         temp |= XHCI_EPCTX_0_MULT_SET(mult - 1);
 2393                         max_packet_count /= mult;
 2394                         break;
 2395                 default:
 2396                         break;
 2397                 }
 2398                 break;
 2399         default:
 2400                 break;
 2401         }
 2402 
 2403         endp->dwEpCtx0 = htole32(temp);
 2404 
 2405         temp =
 2406             XHCI_EPCTX_1_HID_SET(0) |
 2407             XHCI_EPCTX_1_MAXB_SET(max_packet_count) |
 2408             XHCI_EPCTX_1_MAXP_SIZE_SET(max_packet_size);
 2409 
 2410         /*
 2411          * Always enable the "three strikes and you are gone" feature
 2412          * except for ISOCHRONOUS endpoints. This is suggested by
 2413          * section 4.3.3 in the XHCI specification about device slot
 2414          * initialisation.
 2415          */
 2416         if (type != UE_ISOCHRONOUS)
 2417                 temp |= XHCI_EPCTX_1_CERR_SET(3);
 2418 
 2419         switch (type) {
 2420         case UE_CONTROL:
 2421                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
 2422                 break;
 2423         case UE_ISOCHRONOUS:
 2424                 temp |= XHCI_EPCTX_1_EPTYPE_SET(1);
 2425                 break;
 2426         case UE_BULK:
 2427                 temp |= XHCI_EPCTX_1_EPTYPE_SET(2);
 2428                 break;
 2429         default:
 2430                 temp |= XHCI_EPCTX_1_EPTYPE_SET(3);
 2431                 break;
 2432         }
 2433 
 2434         /* check for IN direction */
 2435         if (epno & 1)
 2436                 temp |= XHCI_EPCTX_1_EPTYPE_SET(4);
 2437 
 2438         endp->dwEpCtx1 = htole32(temp);
 2439         endp->qwEpCtx2 = htole64(ring_addr);
 2440 
 2441         switch (edesc->bmAttributes & UE_XFERTYPE) {
 2442         case UE_INTERRUPT:
 2443         case UE_ISOCHRONOUS:
 2444                 temp = XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(max_frame_size) |
 2445                     XHCI_EPCTX_4_AVG_TRB_LEN_SET(MIN(XHCI_PAGE_SIZE,
 2446                     max_frame_size));
 2447                 break;
 2448         case UE_CONTROL:
 2449                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(8);
 2450                 break;
 2451         default:
 2452                 temp = XHCI_EPCTX_4_AVG_TRB_LEN_SET(XHCI_PAGE_SIZE);
 2453                 break;
 2454         }
 2455 
 2456         endp->dwEpCtx4 = htole32(temp);
 2457 
 2458 #ifdef USB_DEBUG
 2459         xhci_dump_endpoint(endp);
 2460 #endif
 2461         usb_pc_cpu_flush(&sc->sc_hw.devs[index].input_pc);
 2462 
 2463         return (0);             /* success */
 2464 }
 2465 
 2466 static usb_error_t
 2467 xhci_configure_endpoint_by_xfer(struct usb_xfer *xfer)
 2468 {
 2469         struct xhci_endpoint_ext *pepext;
 2470         struct usb_endpoint_ss_comp_descriptor *ecomp;
 2471         usb_stream_t x;
 2472 
 2473         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
 2474             xfer->endpoint->edesc);
 2475 
 2476         ecomp = xfer->endpoint->ecomp;
 2477 
 2478         for (x = 0; x != XHCI_MAX_STREAMS; x++) {
 2479                 uint64_t temp;
 2480 
 2481                 /* halt any transfers */
 2482                 pepext->trb[x * XHCI_MAX_TRANSFERS].dwTrb3 = 0;
 2483 
 2484                 /* compute start of TRB ring for stream "x" */
 2485                 temp = pepext->physaddr +
 2486                     (x * XHCI_MAX_TRANSFERS * sizeof(struct xhci_trb)) +
 2487                     XHCI_SCTX_0_SCT_SEC_TR_RING;
 2488 
 2489                 /* make tree structure */
 2490                 pepext->trb[(XHCI_MAX_TRANSFERS *
 2491                     XHCI_MAX_STREAMS) + x].qwTrb0 = htole64(temp);
 2492 
 2493                 /* reserved fields */
 2494                 pepext->trb[(XHCI_MAX_TRANSFERS *
 2495                     XHCI_MAX_STREAMS) + x].dwTrb2 = 0;
 2496                 pepext->trb[(XHCI_MAX_TRANSFERS *
 2497                     XHCI_MAX_STREAMS) + x].dwTrb3 = 0;
 2498         }
 2499         usb_pc_cpu_flush(pepext->page_cache);
 2500 
 2501         return (xhci_configure_endpoint(xfer->xroot->udev,
 2502             xfer->endpoint->edesc, pepext,
 2503             xfer->interval, xfer->max_packet_count,
 2504             (ecomp != NULL) ? UE_GET_SS_ISO_MULT(ecomp->bmAttributes) + 1 : 1,
 2505             usbd_xfer_get_fps_shift(xfer), xfer->max_packet_size,
 2506             xfer->max_frame_size, xfer->endpoint->ep_mode));
 2507 }
 2508 
 2509 static usb_error_t
 2510 xhci_configure_device(struct usb_device *udev)
 2511 {
 2512         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2513         struct usb_page_search buf_inp;
 2514         struct usb_page_cache *pcinp;
 2515         struct xhci_slot_ctx *slot;
 2516         struct usb_device *hubdev;
 2517         uint32_t temp;
 2518         uint32_t route;
 2519         uint32_t rh_port;
 2520         uint8_t is_hub;
 2521         uint8_t index;
 2522         uint8_t depth;
 2523 
 2524         index = udev->controller_slot_id;
 2525 
 2526         DPRINTF("index=%u\n", index);
 2527 
 2528         pcinp = &sc->sc_hw.devs[index].input_pc;
 2529 
 2530         usbd_get_page(pcinp, 0, &buf_inp);
 2531 
 2532         slot = XHCI_GET_CTX(sc, xhci_input_dev_ctx, ctx_slot, buf_inp.buffer);
 2533 
 2534         rh_port = 0;
 2535         route = 0;
 2536 
 2537         /* figure out route string and root HUB port number */
 2538 
 2539         for (hubdev = udev; hubdev != NULL; hubdev = hubdev->parent_hub) {
 2540                 if (hubdev->parent_hub == NULL)
 2541                         break;
 2542 
 2543                 depth = hubdev->parent_hub->depth;
 2544 
 2545                 /*
 2546                  * NOTE: HS/FS/LS devices and the SS root HUB can have
 2547                  * more than 15 ports
 2548                  */
 2549 
 2550                 rh_port = hubdev->port_no;
 2551 
 2552                 if (depth == 0)
 2553                         break;
 2554 
 2555                 if (rh_port > 15)
 2556                         rh_port = 15;
 2557 
 2558                 if (depth < 6)
 2559                         route |= rh_port << (4 * (depth - 1));
 2560         }
 2561 
 2562         DPRINTF("Route=0x%08x\n", route);
 2563 
 2564         temp = XHCI_SCTX_0_ROUTE_SET(route) |
 2565             XHCI_SCTX_0_CTX_NUM_SET(
 2566             sc->sc_hw.devs[index].context_num + 1);
 2567 
 2568         switch (udev->speed) {
 2569         case USB_SPEED_LOW:
 2570                 temp |= XHCI_SCTX_0_SPEED_SET(2);
 2571                 if (udev->parent_hs_hub != NULL &&
 2572                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
 2573                     UDPROTO_HSHUBMTT) {
 2574                         DPRINTF("Device inherits MTT\n");
 2575                         temp |= XHCI_SCTX_0_MTT_SET(1);
 2576                 }
 2577                 break;
 2578         case USB_SPEED_HIGH:
 2579                 temp |= XHCI_SCTX_0_SPEED_SET(3);
 2580                 if (sc->sc_hw.devs[index].nports != 0 &&
 2581                     udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) {
 2582                         DPRINTF("HUB supports MTT\n");
 2583                         temp |= XHCI_SCTX_0_MTT_SET(1);
 2584                 }
 2585                 break;
 2586         case USB_SPEED_FULL:
 2587                 temp |= XHCI_SCTX_0_SPEED_SET(1);
 2588                 if (udev->parent_hs_hub != NULL &&
 2589                     udev->parent_hs_hub->ddesc.bDeviceProtocol ==
 2590                     UDPROTO_HSHUBMTT) {
 2591                         DPRINTF("Device inherits MTT\n");
 2592                         temp |= XHCI_SCTX_0_MTT_SET(1);
 2593                 }
 2594                 break;
 2595         default:
 2596                 temp |= XHCI_SCTX_0_SPEED_SET(4);
 2597                 break;
 2598         }
 2599 
 2600         is_hub = sc->sc_hw.devs[index].nports != 0 &&
 2601             (udev->speed == USB_SPEED_SUPER ||
 2602             udev->speed == USB_SPEED_HIGH);
 2603 
 2604         if (is_hub)
 2605                 temp |= XHCI_SCTX_0_HUB_SET(1);
 2606 
 2607         slot->dwSctx0 = htole32(temp);
 2608 
 2609         temp = XHCI_SCTX_1_RH_PORT_SET(rh_port);
 2610 
 2611         if (is_hub) {
 2612                 temp |= XHCI_SCTX_1_NUM_PORTS_SET(
 2613                     sc->sc_hw.devs[index].nports);
 2614         }
 2615 
 2616         slot->dwSctx1 = htole32(temp);
 2617 
 2618         temp = XHCI_SCTX_2_IRQ_TARGET_SET(0);
 2619 
 2620         if (is_hub) {
 2621                 temp |= XHCI_SCTX_2_TT_THINK_TIME_SET(
 2622                     sc->sc_hw.devs[index].tt);
 2623         }
 2624 
 2625         hubdev = udev->parent_hs_hub;
 2626 
 2627         /* check if we should activate the transaction translator */
 2628         switch (udev->speed) {
 2629         case USB_SPEED_FULL:
 2630         case USB_SPEED_LOW:
 2631                 if (hubdev != NULL) {
 2632                         temp |= XHCI_SCTX_2_TT_HUB_SID_SET(
 2633                             hubdev->controller_slot_id);
 2634                         temp |= XHCI_SCTX_2_TT_PORT_NUM_SET(
 2635                             udev->hs_port_no);
 2636                 }
 2637                 break;
 2638         default:
 2639                 break;
 2640         }
 2641 
 2642         slot->dwSctx2 = htole32(temp);
 2643 
 2644         /*
 2645          * These fields should be initialized to zero, according to
 2646          * XHCI section 6.2.2 - slot context:
 2647          */
 2648         temp = XHCI_SCTX_3_DEV_ADDR_SET(0) |
 2649             XHCI_SCTX_3_SLOT_STATE_SET(0);
 2650 
 2651         slot->dwSctx3 = htole32(temp);
 2652 
 2653 #ifdef USB_DEBUG
 2654         xhci_dump_device(slot);
 2655 #endif
 2656         usb_pc_cpu_flush(pcinp);
 2657 
 2658         return (0);             /* success */
 2659 }
 2660 
 2661 static usb_error_t
 2662 xhci_alloc_device_ext(struct usb_device *udev)
 2663 {
 2664         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2665         struct usb_page_search buf_dev;
 2666         struct usb_page_search buf_ep;
 2667         struct xhci_trb *trb;
 2668         struct usb_page_cache *pc;
 2669         struct usb_page *pg;
 2670         uint64_t addr;
 2671         uint8_t index;
 2672         uint8_t i;
 2673 
 2674         index = udev->controller_slot_id;
 2675 
 2676         pc = &sc->sc_hw.devs[index].device_pc;
 2677         pg = &sc->sc_hw.devs[index].device_pg;
 2678 
 2679         /* need to initialize the page cache */
 2680         pc->tag_parent = sc->sc_bus.dma_parent_tag;
 2681 
 2682         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
 2683             sizeof(struct xhci_dev_ctx64) :
 2684             sizeof(struct xhci_dev_ctx), XHCI_PAGE_SIZE))
 2685                 goto error;
 2686 
 2687         usbd_get_page(pc, 0, &buf_dev);
 2688 
 2689         pc = &sc->sc_hw.devs[index].input_pc;
 2690         pg = &sc->sc_hw.devs[index].input_pg;
 2691 
 2692         /* need to initialize the page cache */
 2693         pc->tag_parent = sc->sc_bus.dma_parent_tag;
 2694 
 2695         if (usb_pc_alloc_mem(pc, pg, sc->sc_ctx_is_64_byte ?
 2696             sizeof(struct xhci_input_dev_ctx64) :
 2697             sizeof(struct xhci_input_dev_ctx), XHCI_PAGE_SIZE)) {
 2698                 goto error;
 2699         }
 2700 
 2701         /* initialize all endpoint LINK TRBs */
 2702 
 2703         for (i = 0; i != XHCI_MAX_ENDPOINTS; i++) {
 2704                 pc = &sc->sc_hw.devs[index].endpoint_pc[i];
 2705                 pg = &sc->sc_hw.devs[index].endpoint_pg[i];
 2706 
 2707                 /* need to initialize the page cache */
 2708                 pc->tag_parent = sc->sc_bus.dma_parent_tag;
 2709 
 2710                 if (usb_pc_alloc_mem(pc, pg,
 2711                     sizeof(struct xhci_dev_endpoint_trbs), XHCI_TRB_ALIGN)) {
 2712                         goto error;
 2713                 }
 2714 
 2715                 /* lookup endpoint TRB ring */
 2716                 usbd_get_page(pc, 0, &buf_ep);
 2717 
 2718                 /* get TRB pointer */
 2719                 trb = buf_ep.buffer;
 2720                 trb += XHCI_MAX_TRANSFERS - 1;
 2721 
 2722                 /* get TRB start address */
 2723                 addr = buf_ep.physaddr;
 2724 
 2725                 /* create LINK TRB */
 2726                 trb->qwTrb0 = htole64(addr);
 2727                 trb->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
 2728                 trb->dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
 2729                     XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
 2730 
 2731                 usb_pc_cpu_flush(pc);
 2732         }
 2733 
 2734         xhci_set_slot_pointer(sc, index, buf_dev.physaddr);
 2735 
 2736         return (0);
 2737 
 2738 error:
 2739         xhci_free_device_ext(udev);
 2740 
 2741         return (USB_ERR_NOMEM);
 2742 }
 2743 
 2744 static void
 2745 xhci_free_device_ext(struct usb_device *udev)
 2746 {
 2747         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2748         uint8_t index;
 2749         uint8_t i;
 2750 
 2751         index = udev->controller_slot_id;
 2752         xhci_set_slot_pointer(sc, index, 0);
 2753 
 2754         usb_pc_free_mem(&sc->sc_hw.devs[index].device_pc);
 2755         usb_pc_free_mem(&sc->sc_hw.devs[index].input_pc);
 2756         for (i = 0; i != XHCI_MAX_ENDPOINTS; i++)
 2757                 usb_pc_free_mem(&sc->sc_hw.devs[index].endpoint_pc[i]);
 2758 }
 2759 
 2760 static struct xhci_endpoint_ext *
 2761 xhci_get_endpoint_ext(struct usb_device *udev, struct usb_endpoint_descriptor *edesc)
 2762 {
 2763         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 2764         struct xhci_endpoint_ext *pepext;
 2765         struct usb_page_cache *pc;
 2766         struct usb_page_search buf_ep;
 2767         uint8_t epno;
 2768         uint8_t index;
 2769 
 2770         epno = edesc->bEndpointAddress;
 2771         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
 2772                 epno |= UE_DIR_IN;
 2773 
 2774         epno = XHCI_EPNO2EPID(epno);
 2775 
 2776         index = udev->controller_slot_id;
 2777 
 2778         pc = &sc->sc_hw.devs[index].endpoint_pc[epno];
 2779 
 2780         usbd_get_page(pc, 0, &buf_ep);
 2781 
 2782         pepext = &sc->sc_hw.devs[index].endp[epno];
 2783         pepext->page_cache = pc;
 2784         pepext->trb = buf_ep.buffer;
 2785         pepext->physaddr = buf_ep.physaddr;
 2786 
 2787         return (pepext);
 2788 }
 2789 
 2790 static void
 2791 xhci_endpoint_doorbell(struct usb_xfer *xfer)
 2792 {
 2793         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
 2794         uint8_t epno;
 2795         uint8_t index;
 2796 
 2797         epno = xfer->endpointno;
 2798         if (xfer->flags_int.control_xfr)
 2799                 epno |= UE_DIR_IN;
 2800 
 2801         epno = XHCI_EPNO2EPID(epno);
 2802         index = xfer->xroot->udev->controller_slot_id;
 2803 
 2804         if (xfer->xroot->udev->flags.self_suspended == 0) {
 2805                 XWRITE4(sc, door, XHCI_DOORBELL(index),
 2806                     epno | XHCI_DB_SID_SET(xfer->stream_id));
 2807         }
 2808 }
 2809 
 2810 static void
 2811 xhci_transfer_remove(struct usb_xfer *xfer, usb_error_t error)
 2812 {
 2813         struct xhci_endpoint_ext *pepext;
 2814 
 2815         if (xfer->flags_int.bandwidth_reclaimed) {
 2816                 xfer->flags_int.bandwidth_reclaimed = 0;
 2817 
 2818                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
 2819                     xfer->endpoint->edesc);
 2820 
 2821                 pepext->trb_used[xfer->stream_id]--;
 2822 
 2823                 pepext->xfer[xfer->qh_pos] = NULL;
 2824 
 2825                 if (error && pepext->trb_running != 0) {
 2826                         pepext->trb_halted = 1;
 2827                         pepext->trb_running = 0;
 2828                 }
 2829         }
 2830 }
 2831 
 2832 static usb_error_t
 2833 xhci_transfer_insert(struct usb_xfer *xfer)
 2834 {
 2835         struct xhci_td *td_first;
 2836         struct xhci_td *td_last;
 2837         struct xhci_trb *trb_link;
 2838         struct xhci_endpoint_ext *pepext;
 2839         uint64_t addr;
 2840         usb_stream_t id;
 2841         uint8_t i;
 2842         uint8_t inext;
 2843         uint8_t trb_limit;
 2844 
 2845         DPRINTFN(8, "\n");
 2846 
 2847         id = xfer->stream_id;
 2848 
 2849         /* check if already inserted */
 2850         if (xfer->flags_int.bandwidth_reclaimed) {
 2851                 DPRINTFN(8, "Already in schedule\n");
 2852                 return (0);
 2853         }
 2854 
 2855         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
 2856             xfer->endpoint->edesc);
 2857 
 2858         td_first = xfer->td_transfer_first;
 2859         td_last = xfer->td_transfer_last;
 2860         addr = pepext->physaddr;
 2861 
 2862         switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
 2863         case UE_CONTROL:
 2864         case UE_INTERRUPT:
 2865                 /* single buffered */
 2866                 trb_limit = 1;
 2867                 break;
 2868         default:
 2869                 /* multi buffered */
 2870                 trb_limit = (XHCI_MAX_TRANSFERS - 2);
 2871                 break;
 2872         }
 2873 
 2874         if (pepext->trb_used[id] >= trb_limit) {
 2875                 DPRINTFN(8, "Too many TDs queued.\n");
 2876                 return (USB_ERR_NOMEM);
 2877         }
 2878 
 2879         /* check if bMaxPacketSize changed */
 2880         if (xfer->flags_int.control_xfr != 0 &&
 2881             pepext->trb_ep_maxp != xfer->endpoint->edesc->wMaxPacketSize[0]) {
 2882                 DPRINTFN(8, "Reconfigure control endpoint\n");
 2883 
 2884                 /* force driver to reconfigure endpoint */
 2885                 pepext->trb_halted = 1;
 2886                 pepext->trb_running = 0;
 2887         }
 2888 
 2889         /* check for stopped condition, after putting transfer on interrupt queue */
 2890         if (pepext->trb_running == 0) {
 2891                 struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
 2892 
 2893                 DPRINTFN(8, "Not running\n");
 2894 
 2895                 /* start configuration */
 2896                 (void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
 2897                     &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
 2898                 return (0);
 2899         }
 2900 
 2901         pepext->trb_used[id]++;
 2902 
 2903         /* get current TRB index */
 2904         i = pepext->trb_index[id];
 2905 
 2906         /* get next TRB index */
 2907         inext = (i + 1);
 2908 
 2909         /* the last entry of the ring is a hardcoded link TRB */
 2910         if (inext >= (XHCI_MAX_TRANSFERS - 1))
 2911                 inext = 0;
 2912 
 2913         /* store next TRB index, before stream ID offset is added */
 2914         pepext->trb_index[id] = inext;
 2915 
 2916         /* offset for stream */
 2917         i += id * XHCI_MAX_TRANSFERS;
 2918         inext += id * XHCI_MAX_TRANSFERS;
 2919 
 2920         /* compute terminating return address */
 2921         addr += (inext * sizeof(struct xhci_trb));
 2922 
 2923         /* compute link TRB pointer */
 2924         trb_link = td_last->td_trb + td_last->ntrb;
 2925 
 2926         /* update next pointer of last link TRB */
 2927         trb_link->qwTrb0 = htole64(addr);
 2928         trb_link->dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
 2929         trb_link->dwTrb3 = htole32(XHCI_TRB_3_IOC_BIT |
 2930             XHCI_TRB_3_CYCLE_BIT |
 2931             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
 2932 
 2933 #ifdef USB_DEBUG
 2934         xhci_dump_trb(&td_last->td_trb[td_last->ntrb]);
 2935 #endif
 2936         usb_pc_cpu_flush(td_last->page_cache);
 2937 
 2938         /* write ahead chain end marker */
 2939 
 2940         pepext->trb[inext].qwTrb0 = 0;
 2941         pepext->trb[inext].dwTrb2 = 0;
 2942         pepext->trb[inext].dwTrb3 = 0;
 2943 
 2944         /* update next pointer of link TRB */
 2945 
 2946         pepext->trb[i].qwTrb0 = htole64((uint64_t)td_first->td_self);
 2947         pepext->trb[i].dwTrb2 = htole32(XHCI_TRB_2_IRQ_SET(0));
 2948 
 2949 #ifdef USB_DEBUG
 2950         xhci_dump_trb(&pepext->trb[i]);
 2951 #endif
 2952         usb_pc_cpu_flush(pepext->page_cache);
 2953 
 2954         /* toggle cycle bit which activates the transfer chain */
 2955 
 2956         pepext->trb[i].dwTrb3 = htole32(XHCI_TRB_3_CYCLE_BIT |
 2957             XHCI_TRB_3_TYPE_SET(XHCI_TRB_TYPE_LINK));
 2958 
 2959         usb_pc_cpu_flush(pepext->page_cache);
 2960 
 2961         DPRINTF("qh_pos = %u\n", i);
 2962 
 2963         pepext->xfer[i] = xfer;
 2964 
 2965         xfer->qh_pos = i;
 2966 
 2967         xfer->flags_int.bandwidth_reclaimed = 1;
 2968 
 2969         xhci_endpoint_doorbell(xfer);
 2970 
 2971         return (0);
 2972 }
 2973 
 2974 static void
 2975 xhci_root_intr(struct xhci_softc *sc)
 2976 {
 2977         uint16_t i;
 2978 
 2979         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
 2980 
 2981         /* clear any old interrupt data */
 2982         memset(sc->sc_hub_idata, 0, sizeof(sc->sc_hub_idata));
 2983 
 2984         for (i = 1; i <= sc->sc_noport; i++) {
 2985                 /* pick out CHANGE bits from the status register */
 2986                 if (XREAD4(sc, oper, XHCI_PORTSC(i)) & (
 2987                     XHCI_PS_CSC | XHCI_PS_PEC |
 2988                     XHCI_PS_OCC | XHCI_PS_WRC |
 2989                     XHCI_PS_PRC | XHCI_PS_PLC |
 2990                     XHCI_PS_CEC)) {
 2991                         sc->sc_hub_idata[i / 8] |= 1 << (i % 8);
 2992                         DPRINTF("port %d changed\n", i);
 2993                 }
 2994         }
 2995         uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
 2996             sizeof(sc->sc_hub_idata));
 2997 }
 2998 
 2999 /*------------------------------------------------------------------------*
 3000  *      xhci_device_done - XHCI done handler
 3001  *
 3002  * NOTE: This function can be called two times in a row on
 3003  * the same USB transfer. From close and from interrupt.
 3004  *------------------------------------------------------------------------*/
 3005 static void
 3006 xhci_device_done(struct usb_xfer *xfer, usb_error_t error)
 3007 {
 3008         DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
 3009             xfer, xfer->endpoint, error);
 3010 
 3011         /* remove transfer from HW queue */
 3012         xhci_transfer_remove(xfer, error);
 3013 
 3014         /* dequeue transfer and start next transfer */
 3015         usbd_transfer_done(xfer, error);
 3016 }
 3017 
 3018 /*------------------------------------------------------------------------*
 3019  * XHCI data transfer support (generic type)
 3020  *------------------------------------------------------------------------*/
 3021 static void
 3022 xhci_device_generic_open(struct usb_xfer *xfer)
 3023 {
 3024         DPRINTF("\n");
 3025 }
 3026 
 3027 static void
 3028 xhci_device_generic_close(struct usb_xfer *xfer)
 3029 {
 3030         DPRINTF("\n");
 3031 
 3032         xhci_device_done(xfer, USB_ERR_CANCELLED);
 3033 }
 3034 
 3035 static void
 3036 xhci_device_generic_multi_enter(struct usb_endpoint *ep,
 3037     usb_stream_t stream_id, struct usb_xfer *enter_xfer)
 3038 {
 3039         struct usb_xfer *xfer;
 3040 
 3041         /* check if there is a current transfer */
 3042         xfer = ep->endpoint_q[stream_id].curr;
 3043         if (xfer == NULL)
 3044                 return;
 3045 
 3046         /*
 3047          * Check if the current transfer is started and then pickup
 3048          * the next one, if any. Else wait for next start event due to
 3049          * block on failure feature.
 3050          */
 3051         if (!xfer->flags_int.bandwidth_reclaimed)
 3052                 return;
 3053 
 3054         xfer = TAILQ_FIRST(&ep->endpoint_q[stream_id].head);
 3055         if (xfer == NULL) {
 3056                 /*
 3057                  * In case of enter we have to consider that the
 3058                  * transfer is queued by the USB core after the enter
 3059                  * method is called.
 3060                  */
 3061                 xfer = enter_xfer;
 3062 
 3063                 if (xfer == NULL)
 3064                         return;
 3065         }
 3066 
 3067         /* try to multi buffer */
 3068         xhci_transfer_insert(xfer);
 3069 }
 3070 
 3071 static void
 3072 xhci_device_generic_enter(struct usb_xfer *xfer)
 3073 {
 3074         DPRINTF("\n");
 3075 
 3076         /* set up TD's and QH */
 3077         xhci_setup_generic_chain(xfer);
 3078 
 3079         xhci_device_generic_multi_enter(xfer->endpoint,
 3080             xfer->stream_id, xfer);
 3081 }
 3082 
 3083 static void
 3084 xhci_device_generic_start(struct usb_xfer *xfer)
 3085 {
 3086         DPRINTF("\n");
 3087 
 3088         /* try to insert xfer on HW queue */
 3089         xhci_transfer_insert(xfer);
 3090 
 3091         /* try to multi buffer */
 3092         xhci_device_generic_multi_enter(xfer->endpoint,
 3093             xfer->stream_id, NULL);
 3094 
 3095         /* add transfer last on interrupt queue */
 3096         usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
 3097 
 3098         /* start timeout, if any */
 3099         if (xfer->timeout != 0)
 3100                 usbd_transfer_timeout_ms(xfer, &xhci_timeout, xfer->timeout);
 3101 }
 3102 
 3103 static const struct usb_pipe_methods xhci_device_generic_methods =
 3104 {
 3105         .open = xhci_device_generic_open,
 3106         .close = xhci_device_generic_close,
 3107         .enter = xhci_device_generic_enter,
 3108         .start = xhci_device_generic_start,
 3109 };
 3110 
 3111 /*------------------------------------------------------------------------*
 3112  * xhci root HUB support
 3113  *------------------------------------------------------------------------*
 3114  * Simulate a hardware HUB by handling all the necessary requests.
 3115  *------------------------------------------------------------------------*/
 3116 #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) }
 3117 
 3118 static const
 3119 struct usb_device_descriptor xhci_devd =
 3120 {
 3121         .bLength = sizeof(xhci_devd),
 3122         .bDescriptorType = UDESC_DEVICE,        /* type */
 3123         HSETW(.bcdUSB, 0x0300),                 /* USB version */
 3124         .bDeviceClass = UDCLASS_HUB,            /* class */
 3125         .bDeviceSubClass = UDSUBCLASS_HUB,      /* subclass */
 3126         .bDeviceProtocol = UDPROTO_SSHUB,       /* protocol */
 3127         .bMaxPacketSize = 9,                    /* max packet size */
 3128         HSETW(.idVendor, 0x0000),               /* vendor */
 3129         HSETW(.idProduct, 0x0000),              /* product */
 3130         HSETW(.bcdDevice, 0x0100),              /* device version */
 3131         .iManufacturer = 1,
 3132         .iProduct = 2,
 3133         .iSerialNumber = 0,
 3134         .bNumConfigurations = 1,                /* # of configurations */
 3135 };
 3136 
 3137 static const
 3138 struct xhci_bos_desc xhci_bosd = {
 3139         .bosd = {
 3140                 .bLength = sizeof(xhci_bosd.bosd),
 3141                 .bDescriptorType = UDESC_BOS,
 3142                 HSETW(.wTotalLength, sizeof(xhci_bosd)),
 3143                 .bNumDeviceCaps = 3,
 3144         },
 3145         .usb2extd = {
 3146                 .bLength = sizeof(xhci_bosd.usb2extd),
 3147                 .bDescriptorType = 1,
 3148                 .bDevCapabilityType = 2,
 3149                 .bmAttributes[0] = 2,
 3150         },
 3151         .usbdcd = {
 3152                 .bLength = sizeof(xhci_bosd.usbdcd),
 3153                 .bDescriptorType = UDESC_DEVICE_CAPABILITY,
 3154                 .bDevCapabilityType = 3,
 3155                 .bmAttributes = 0, /* XXX */
 3156                 HSETW(.wSpeedsSupported, 0x000C),
 3157                 .bFunctionalitySupport = 8,
 3158                 .bU1DevExitLat = 255,   /* dummy - not used */
 3159                 .wU2DevExitLat = { 0x00, 0x08 },
 3160         },
 3161         .cidd = {
 3162                 .bLength = sizeof(xhci_bosd.cidd),
 3163                 .bDescriptorType = 1,
 3164                 .bDevCapabilityType = 4,
 3165                 .bReserved = 0,
 3166                 .bContainerID = 0, /* XXX */
 3167         },
 3168 };
 3169 
 3170 static const
 3171 struct xhci_config_desc xhci_confd = {
 3172         .confd = {
 3173                 .bLength = sizeof(xhci_confd.confd),
 3174                 .bDescriptorType = UDESC_CONFIG,
 3175                 .wTotalLength[0] = sizeof(xhci_confd),
 3176                 .bNumInterface = 1,
 3177                 .bConfigurationValue = 1,
 3178                 .iConfiguration = 0,
 3179                 .bmAttributes = UC_SELF_POWERED,
 3180                 .bMaxPower = 0          /* max power */
 3181         },
 3182         .ifcd = {
 3183                 .bLength = sizeof(xhci_confd.ifcd),
 3184                 .bDescriptorType = UDESC_INTERFACE,
 3185                 .bNumEndpoints = 1,
 3186                 .bInterfaceClass = UICLASS_HUB,
 3187                 .bInterfaceSubClass = UISUBCLASS_HUB,
 3188                 .bInterfaceProtocol = 0,
 3189         },
 3190         .endpd = {
 3191                 .bLength = sizeof(xhci_confd.endpd),
 3192                 .bDescriptorType = UDESC_ENDPOINT,
 3193                 .bEndpointAddress = UE_DIR_IN | XHCI_INTR_ENDPT,
 3194                 .bmAttributes = UE_INTERRUPT,
 3195                 .wMaxPacketSize[0] = 2,         /* max 15 ports */
 3196                 .bInterval = 255,
 3197         },
 3198         .endpcd = {
 3199                 .bLength = sizeof(xhci_confd.endpcd),
 3200                 .bDescriptorType = UDESC_ENDPOINT_SS_COMP,
 3201                 .bMaxBurst = 0,
 3202                 .bmAttributes = 0,
 3203         },
 3204 };
 3205 
 3206 static const
 3207 struct usb_hub_ss_descriptor xhci_hubd = {
 3208         .bLength = sizeof(xhci_hubd),
 3209         .bDescriptorType = UDESC_SS_HUB,
 3210 };
 3211 
 3212 static usb_error_t
 3213 xhci_roothub_exec(struct usb_device *udev,
 3214     struct usb_device_request *req, const void **pptr, uint16_t *plength)
 3215 {
 3216         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 3217         const char *str_ptr;
 3218         const void *ptr;
 3219         uint32_t port;
 3220         uint32_t v;
 3221         uint16_t len;
 3222         uint16_t i;
 3223         uint16_t value;
 3224         uint16_t index;
 3225         uint8_t j;
 3226         usb_error_t err;
 3227 
 3228         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
 3229 
 3230         /* buffer reset */
 3231         ptr = (const void *)&sc->sc_hub_desc;
 3232         len = 0;
 3233         err = 0;
 3234 
 3235         value = UGETW(req->wValue);
 3236         index = UGETW(req->wIndex);
 3237 
 3238         DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
 3239             "wValue=0x%04x wIndex=0x%04x\n",
 3240             req->bmRequestType, req->bRequest,
 3241             UGETW(req->wLength), value, index);
 3242 
 3243 #define C(x,y) ((x) | ((y) << 8))
 3244         switch (C(req->bRequest, req->bmRequestType)) {
 3245         case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
 3246         case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
 3247         case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
 3248                 /*
 3249                  * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
 3250                  * for the integrated root hub.
 3251                  */
 3252                 break;
 3253         case C(UR_GET_CONFIG, UT_READ_DEVICE):
 3254                 len = 1;
 3255                 sc->sc_hub_desc.temp[0] = sc->sc_conf;
 3256                 break;
 3257         case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
 3258                 switch (value >> 8) {
 3259                 case UDESC_DEVICE:
 3260                         if ((value & 0xff) != 0) {
 3261                                 err = USB_ERR_IOERROR;
 3262                                 goto done;
 3263                         }
 3264                         len = sizeof(xhci_devd);
 3265                         ptr = (const void *)&xhci_devd;
 3266                         break;
 3267 
 3268                 case UDESC_BOS:
 3269                         if ((value & 0xff) != 0) {
 3270                                 err = USB_ERR_IOERROR;
 3271                                 goto done;
 3272                         }
 3273                         len = sizeof(xhci_bosd);
 3274                         ptr = (const void *)&xhci_bosd;
 3275                         break;
 3276 
 3277                 case UDESC_CONFIG:
 3278                         if ((value & 0xff) != 0) {
 3279                                 err = USB_ERR_IOERROR;
 3280                                 goto done;
 3281                         }
 3282                         len = sizeof(xhci_confd);
 3283                         ptr = (const void *)&xhci_confd;
 3284                         break;
 3285 
 3286                 case UDESC_STRING:
 3287                         switch (value & 0xff) {
 3288                         case 0: /* Language table */
 3289                                 str_ptr = "\001";
 3290                                 break;
 3291 
 3292                         case 1: /* Vendor */
 3293                                 str_ptr = sc->sc_vendor;
 3294                                 break;
 3295 
 3296                         case 2: /* Product */
 3297                                 str_ptr = "XHCI root HUB";
 3298                                 break;
 3299 
 3300                         default:
 3301                                 str_ptr = "";
 3302                                 break;
 3303                         }
 3304 
 3305                         len = usb_make_str_desc(
 3306                             sc->sc_hub_desc.temp,
 3307                             sizeof(sc->sc_hub_desc.temp),
 3308                             str_ptr);
 3309                         break;
 3310 
 3311                 default:
 3312                         err = USB_ERR_IOERROR;
 3313                         goto done;
 3314                 }
 3315                 break;
 3316         case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
 3317                 len = 1;
 3318                 sc->sc_hub_desc.temp[0] = 0;
 3319                 break;
 3320         case C(UR_GET_STATUS, UT_READ_DEVICE):
 3321                 len = 2;
 3322                 USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
 3323                 break;
 3324         case C(UR_GET_STATUS, UT_READ_INTERFACE):
 3325         case C(UR_GET_STATUS, UT_READ_ENDPOINT):
 3326                 len = 2;
 3327                 USETW(sc->sc_hub_desc.stat.wStatus, 0);
 3328                 break;
 3329         case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
 3330                 if (value >= XHCI_MAX_DEVICES) {
 3331                         err = USB_ERR_IOERROR;
 3332                         goto done;
 3333                 }
 3334                 break;
 3335         case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
 3336                 if (value != 0 && value != 1) {
 3337                         err = USB_ERR_IOERROR;
 3338                         goto done;
 3339                 }
 3340                 sc->sc_conf = value;
 3341                 break;
 3342         case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
 3343                 break;
 3344         case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
 3345         case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
 3346         case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
 3347                 err = USB_ERR_IOERROR;
 3348                 goto done;
 3349         case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
 3350                 break;
 3351         case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
 3352                 break;
 3353                 /* Hub requests */
 3354         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
 3355                 break;
 3356         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
 3357                 DPRINTFN(9, "UR_CLEAR_PORT_FEATURE\n");
 3358 
 3359                 if ((index < 1) ||
 3360                     (index > sc->sc_noport)) {
 3361                         err = USB_ERR_IOERROR;
 3362                         goto done;
 3363                 }
 3364                 port = XHCI_PORTSC(index);
 3365 
 3366                 v = XREAD4(sc, oper, port);
 3367                 i = XHCI_PS_PLS_GET(v);
 3368                 v &= ~XHCI_PS_CLEAR;
 3369 
 3370                 switch (value) {
 3371                 case UHF_C_BH_PORT_RESET:
 3372                         XWRITE4(sc, oper, port, v | XHCI_PS_WRC);
 3373                         break;
 3374                 case UHF_C_PORT_CONFIG_ERROR:
 3375                         XWRITE4(sc, oper, port, v | XHCI_PS_CEC);
 3376                         break;
 3377                 case UHF_C_PORT_SUSPEND:
 3378                 case UHF_C_PORT_LINK_STATE:
 3379                         XWRITE4(sc, oper, port, v | XHCI_PS_PLC);
 3380                         break;
 3381                 case UHF_C_PORT_CONNECTION:
 3382                         XWRITE4(sc, oper, port, v | XHCI_PS_CSC);
 3383                         break;
 3384                 case UHF_C_PORT_ENABLE:
 3385                         XWRITE4(sc, oper, port, v | XHCI_PS_PEC);
 3386                         break;
 3387                 case UHF_C_PORT_OVER_CURRENT:
 3388                         XWRITE4(sc, oper, port, v | XHCI_PS_OCC);
 3389                         break;
 3390                 case UHF_C_PORT_RESET:
 3391                         XWRITE4(sc, oper, port, v | XHCI_PS_PRC);
 3392                         break;
 3393                 case UHF_PORT_ENABLE:
 3394                         if ((sc->sc_quirks & XHCI_QUIRK_DISABLE_PORT_PED) == 0)
 3395                                 XWRITE4(sc, oper, port, v | XHCI_PS_PED);
 3396                         break;
 3397                 case UHF_PORT_POWER:
 3398                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PP);
 3399                         break;
 3400                 case UHF_PORT_INDICATOR:
 3401                         XWRITE4(sc, oper, port, v & ~XHCI_PS_PIC_SET(3));
 3402                         break;
 3403                 case UHF_PORT_SUSPEND:
 3404 
 3405                         /* U3 -> U15 */
 3406                         if (i == 3) {
 3407                                 XWRITE4(sc, oper, port, v |
 3408                                     XHCI_PS_PLS_SET(0xF) | XHCI_PS_LWS);
 3409                         }
 3410 
 3411                         /* wait 20ms for resume sequence to complete */
 3412                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
 3413 
 3414                         /* U0 */
 3415                         XWRITE4(sc, oper, port, v |
 3416                             XHCI_PS_PLS_SET(0) | XHCI_PS_LWS);
 3417                         break;
 3418                 default:
 3419                         err = USB_ERR_IOERROR;
 3420                         goto done;
 3421                 }
 3422                 break;
 3423 
 3424         case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
 3425                 if ((value & 0xff) != 0) {
 3426                         err = USB_ERR_IOERROR;
 3427                         goto done;
 3428                 }
 3429 
 3430                 v = XREAD4(sc, capa, XHCI_HCSPARAMS0);
 3431 
 3432                 sc->sc_hub_desc.hubd = xhci_hubd;
 3433 
 3434                 sc->sc_hub_desc.hubd.bNbrPorts = sc->sc_noport;
 3435 
 3436                 if (XHCI_HCS0_PPC(v))
 3437                         i = UHD_PWR_INDIVIDUAL;
 3438                 else
 3439                         i = UHD_PWR_GANGED;
 3440 
 3441                 if (XHCI_HCS0_PIND(v))
 3442                         i |= UHD_PORT_IND;
 3443 
 3444                 i |= UHD_OC_INDIVIDUAL;
 3445 
 3446                 USETW(sc->sc_hub_desc.hubd.wHubCharacteristics, i);
 3447 
 3448                 /* see XHCI section 5.4.9: */
 3449                 sc->sc_hub_desc.hubd.bPwrOn2PwrGood = 10;
 3450 
 3451                 for (j = 1; j <= sc->sc_noport; j++) {
 3452                         v = XREAD4(sc, oper, XHCI_PORTSC(j));
 3453                         if (v & XHCI_PS_DR) {
 3454                                 sc->sc_hub_desc.hubd.
 3455                                     DeviceRemovable[j / 8] |= 1U << (j % 8);
 3456                         }
 3457                 }
 3458                 len = sc->sc_hub_desc.hubd.bLength;
 3459                 break;
 3460 
 3461         case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
 3462                 len = 16;
 3463                 memset(sc->sc_hub_desc.temp, 0, 16);
 3464                 break;
 3465 
 3466         case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
 3467                 DPRINTFN(9, "UR_GET_STATUS i=%d\n", index);
 3468 
 3469                 if ((index < 1) ||
 3470                     (index > sc->sc_noport)) {
 3471                         err = USB_ERR_IOERROR;
 3472                         goto done;
 3473                 }
 3474 
 3475                 v = XREAD4(sc, oper, XHCI_PORTSC(index));
 3476 
 3477                 DPRINTFN(9, "port status=0x%08x\n", v);
 3478 
 3479                 i = UPS_PORT_LINK_STATE_SET(XHCI_PS_PLS_GET(v));
 3480 
 3481                 switch (XHCI_PS_SPEED_GET(v)) {
 3482                 case XHCI_PS_SPEED_HIGH:
 3483                         i |= UPS_HIGH_SPEED;
 3484                         break;
 3485                 case XHCI_PS_SPEED_LOW:
 3486                         i |= UPS_LOW_SPEED;
 3487                         break;
 3488                 case XHCI_PS_SPEED_FULL:
 3489                         /* FULL speed */
 3490                         break;
 3491                 default:
 3492                         i |= UPS_OTHER_SPEED;
 3493                         break;
 3494                 }
 3495 
 3496                 if (v & XHCI_PS_CCS)
 3497                         i |= UPS_CURRENT_CONNECT_STATUS;
 3498                 if (v & XHCI_PS_PED)
 3499                         i |= UPS_PORT_ENABLED;
 3500                 if (v & XHCI_PS_OCA)
 3501                         i |= UPS_OVERCURRENT_INDICATOR;
 3502                 if (v & XHCI_PS_PR)
 3503                         i |= UPS_RESET;
 3504 #if 0
 3505                 if (v & XHCI_PS_PP)
 3506                         /* XXX undefined */
 3507 #endif
 3508                 USETW(sc->sc_hub_desc.ps.wPortStatus, i);
 3509 
 3510                 i = 0;
 3511                 if (v & XHCI_PS_CSC)
 3512                         i |= UPS_C_CONNECT_STATUS;
 3513                 if (v & XHCI_PS_PEC)
 3514                         i |= UPS_C_PORT_ENABLED;
 3515                 if (v & XHCI_PS_OCC)
 3516                         i |= UPS_C_OVERCURRENT_INDICATOR;
 3517                 if (v & XHCI_PS_WRC)
 3518                         i |= UPS_C_BH_PORT_RESET;
 3519                 if (v & XHCI_PS_PRC)
 3520                         i |= UPS_C_PORT_RESET;
 3521                 if (v & XHCI_PS_PLC)
 3522                         i |= UPS_C_PORT_LINK_STATE;
 3523                 if (v & XHCI_PS_CEC)
 3524                         i |= UPS_C_PORT_CONFIG_ERROR;
 3525 
 3526                 USETW(sc->sc_hub_desc.ps.wPortChange, i);
 3527                 len = sizeof(sc->sc_hub_desc.ps);
 3528                 break;
 3529 
 3530         case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
 3531                 err = USB_ERR_IOERROR;
 3532                 goto done;
 3533 
 3534         case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
 3535                 break;
 3536 
 3537         case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
 3538 
 3539                 i = index >> 8;
 3540                 index &= 0x00FF;
 3541 
 3542                 if ((index < 1) ||
 3543                     (index > sc->sc_noport)) {
 3544                         err = USB_ERR_IOERROR;
 3545                         goto done;
 3546                 }
 3547 
 3548                 port = XHCI_PORTSC(index);
 3549                 v = XREAD4(sc, oper, port) & ~XHCI_PS_CLEAR;
 3550 
 3551                 switch (value) {
 3552                 case UHF_PORT_U1_TIMEOUT:
 3553                         if (XHCI_PS_SPEED_GET(v) < XHCI_PS_SPEED_SS) {
 3554                                 err = USB_ERR_IOERROR;
 3555                                 goto done;
 3556                         }
 3557                         port = XHCI_PORTPMSC(index);
 3558                         v = XREAD4(sc, oper, port);
 3559                         v &= ~XHCI_PM3_U1TO_SET(0xFF);
 3560                         v |= XHCI_PM3_U1TO_SET(i);
 3561                         XWRITE4(sc, oper, port, v);
 3562                         break;
 3563                 case UHF_PORT_U2_TIMEOUT:
 3564                         if (XHCI_PS_SPEED_GET(v) < XHCI_PS_SPEED_SS) {
 3565                                 err = USB_ERR_IOERROR;
 3566                                 goto done;
 3567                         }
 3568                         port = XHCI_PORTPMSC(index);
 3569                         v = XREAD4(sc, oper, port);
 3570                         v &= ~XHCI_PM3_U2TO_SET(0xFF);
 3571                         v |= XHCI_PM3_U2TO_SET(i);
 3572                         XWRITE4(sc, oper, port, v);
 3573                         break;
 3574                 case UHF_BH_PORT_RESET:
 3575                         XWRITE4(sc, oper, port, v | XHCI_PS_WPR);
 3576                         break;
 3577                 case UHF_PORT_LINK_STATE:
 3578                         XWRITE4(sc, oper, port, v |
 3579                             XHCI_PS_PLS_SET(i) | XHCI_PS_LWS);
 3580                         /* 4ms settle time */
 3581                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250);
 3582                         break;
 3583                 case UHF_PORT_ENABLE:
 3584                         DPRINTFN(3, "set port enable %d\n", index);
 3585                         break;
 3586                 case UHF_PORT_SUSPEND:
 3587                         DPRINTFN(6, "suspend port %u (LPM=%u)\n", index, i);
 3588                         j = XHCI_PS_SPEED_GET(v);
 3589                         if (j == 0 || j >= XHCI_PS_SPEED_SS) {
 3590                                 /* non-supported speed */
 3591                                 err = USB_ERR_IOERROR;
 3592                                 goto done;
 3593                         }
 3594                         XWRITE4(sc, oper, port, v |
 3595                             XHCI_PS_PLS_SET(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
 3596                         break;
 3597                 case UHF_PORT_RESET:
 3598                         DPRINTFN(6, "reset port %d\n", index);
 3599                         XWRITE4(sc, oper, port, v | XHCI_PS_PR);
 3600                         break;
 3601                 case UHF_PORT_POWER:
 3602                         DPRINTFN(3, "set port power %d\n", index);
 3603                         XWRITE4(sc, oper, port, v | XHCI_PS_PP);
 3604                         break;
 3605                 case UHF_PORT_TEST:
 3606                         DPRINTFN(3, "set port test %d\n", index);
 3607                         break;
 3608                 case UHF_PORT_INDICATOR:
 3609                         DPRINTFN(3, "set port indicator %d\n", index);
 3610 
 3611                         v &= ~XHCI_PS_PIC_SET(3);
 3612                         v |= XHCI_PS_PIC_SET(1);
 3613 
 3614                         XWRITE4(sc, oper, port, v);
 3615                         break;
 3616                 default:
 3617                         err = USB_ERR_IOERROR;
 3618                         goto done;
 3619                 }
 3620                 break;
 3621 
 3622         case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
 3623         case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
 3624         case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
 3625         case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
 3626                 break;
 3627         default:
 3628                 err = USB_ERR_IOERROR;
 3629                 goto done;
 3630         }
 3631 done:
 3632         *plength = len;
 3633         *pptr = ptr;
 3634         return (err);
 3635 }
 3636 
 3637 static void
 3638 xhci_xfer_setup(struct usb_setup_params *parm)
 3639 {
 3640         struct usb_page_search page_info;
 3641         struct usb_page_cache *pc;
 3642         struct usb_xfer *xfer;
 3643         void *last_obj;
 3644         uint32_t ntd;
 3645         uint32_t n;
 3646 
 3647         xfer = parm->curr_xfer;
 3648 
 3649         /*
 3650          * The proof for the "ntd" formula is illustrated like this:
 3651          *
 3652          * +------------------------------------+
 3653          * |                                    |
 3654          * |         |remainder ->              |
 3655          * |   +-----+---+                      |
 3656          * |   | xxx | x | frm 0                |
 3657          * |   +-----+---++                     |
 3658          * |   | xxx | xx | frm 1               |
 3659          * |   +-----+----+                     |
 3660          * |            ...                     |
 3661          * +------------------------------------+
 3662          *
 3663          * "xxx" means a completely full USB transfer descriptor
 3664          *
 3665          * "x" and "xx" means a short USB packet
 3666          *
 3667          * For the remainder of an USB transfer modulo
 3668          * "max_data_length" we need two USB transfer descriptors.
 3669          * One to transfer the remaining data and one to finalise with
 3670          * a zero length packet in case the "force_short_xfer" flag is
 3671          * set. We only need two USB transfer descriptors in the case
 3672          * where the transfer length of the first one is a factor of
 3673          * "max_frame_size". The rest of the needed USB transfer
 3674          * descriptors is given by the buffer size divided by the
 3675          * maximum data payload.
 3676          */
 3677         parm->hc_max_packet_size = 0x400;
 3678         parm->hc_max_packet_count = 16 * 3;
 3679         parm->hc_max_frame_size = XHCI_TD_PAYLOAD_MAX;
 3680 
 3681         xfer->flags_int.bdma_enable = 1;
 3682 
 3683         usbd_transfer_setup_sub(parm);
 3684 
 3685         if (xfer->flags_int.isochronous_xfr) {
 3686                 ntd = ((1 * xfer->nframes)
 3687                     + (xfer->max_data_length / xfer->max_hc_frame_size));
 3688         } else if (xfer->flags_int.control_xfr) {
 3689                 ntd = ((2 * xfer->nframes) + 1  /* STATUS */
 3690                     + (xfer->max_data_length / xfer->max_hc_frame_size));
 3691         } else {
 3692                 ntd = ((2 * xfer->nframes)
 3693                     + (xfer->max_data_length / xfer->max_hc_frame_size));
 3694         }
 3695 
 3696 alloc_dma_set:
 3697 
 3698         if (parm->err)
 3699                 return;
 3700 
 3701         /*
 3702          * Allocate queue heads and transfer descriptors
 3703          */
 3704         last_obj = NULL;
 3705 
 3706         if (usbd_transfer_setup_sub_malloc(
 3707             parm, &pc, sizeof(struct xhci_td),
 3708             XHCI_TD_ALIGN, ntd)) {
 3709                 parm->err = USB_ERR_NOMEM;
 3710                 return;
 3711         }
 3712         if (parm->buf) {
 3713                 for (n = 0; n != ntd; n++) {
 3714                         struct xhci_td *td;
 3715 
 3716                         usbd_get_page(pc + n, 0, &page_info);
 3717 
 3718                         td = page_info.buffer;
 3719 
 3720                         /* init TD */
 3721                         td->td_self = page_info.physaddr;
 3722                         td->obj_next = last_obj;
 3723                         td->page_cache = pc + n;
 3724 
 3725                         last_obj = td;
 3726 
 3727                         usb_pc_cpu_flush(pc + n);
 3728                 }
 3729         }
 3730         xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
 3731 
 3732         if (!xfer->flags_int.curr_dma_set) {
 3733                 xfer->flags_int.curr_dma_set = 1;
 3734                 goto alloc_dma_set;
 3735         }
 3736 }
 3737 
 3738 static uint8_t
 3739 xhci_get_endpoint_state(struct usb_device *udev, uint8_t epno)
 3740 {
 3741         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 3742         struct usb_page_search buf_dev;
 3743         struct xhci_hw_dev *hdev;
 3744         struct xhci_endp_ctx *endp;
 3745         uint32_t temp;
 3746 
 3747         MPASS(epno != 0);
 3748 
 3749         hdev =  &sc->sc_hw.devs[udev->controller_slot_id];
 3750 
 3751         usbd_get_page(&hdev->device_pc, 0, &buf_dev);
 3752         endp = XHCI_GET_CTX(sc, xhci_dev_ctx, ctx_ep[epno - 1],
 3753             buf_dev.buffer);
 3754         usb_pc_cpu_invalidate(&hdev->device_pc);
 3755 
 3756         temp = le32toh(endp->dwEpCtx0);
 3757 
 3758         return (XHCI_EPCTX_0_EPSTATE_GET(temp));
 3759 }
 3760 
 3761 static usb_error_t
 3762 xhci_configure_reset_endpoint(struct usb_xfer *xfer)
 3763 {
 3764         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
 3765         struct usb_page_search buf_inp;
 3766         struct usb_device *udev;
 3767         struct xhci_endpoint_ext *pepext;
 3768         struct usb_endpoint_descriptor *edesc;
 3769         struct usb_page_cache *pcinp;
 3770         usb_error_t err;
 3771         usb_stream_t stream_id;
 3772         uint32_t mask;
 3773         uint8_t index;
 3774         uint8_t epno;
 3775         uint8_t drop;
 3776 
 3777         pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
 3778             xfer->endpoint->edesc);
 3779 
 3780         udev = xfer->xroot->udev;
 3781         index = udev->controller_slot_id;
 3782 
 3783         pcinp = &sc->sc_hw.devs[index].input_pc;
 3784 
 3785         usbd_get_page(pcinp, 0, &buf_inp);
 3786 
 3787         edesc = xfer->endpoint->edesc;
 3788 
 3789         epno = edesc->bEndpointAddress;
 3790         stream_id = xfer->stream_id;
 3791 
 3792         if ((edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL)
 3793                 epno |= UE_DIR_IN;
 3794 
 3795         epno = XHCI_EPNO2EPID(epno);
 3796 
 3797         if (epno == 0)
 3798                 return (USB_ERR_NO_PIPE);               /* invalid */
 3799 
 3800         XHCI_CMD_LOCK(sc);
 3801 
 3802         /* configure endpoint */
 3803 
 3804         err = xhci_configure_endpoint_by_xfer(xfer);
 3805 
 3806         if (err != 0) {
 3807                 XHCI_CMD_UNLOCK(sc);
 3808                 return (err);
 3809         }
 3810 
 3811         /*
 3812          * Get the endpoint into the stopped state according to the
 3813          * endpoint context state diagram in the XHCI specification:
 3814          */
 3815         switch (xhci_get_endpoint_state(udev, epno)) {
 3816         case XHCI_EPCTX_0_EPSTATE_DISABLED:
 3817                 drop = 0;
 3818                 break;
 3819         case XHCI_EPCTX_0_EPSTATE_STOPPED:
 3820                 drop = 1;
 3821                 break;
 3822         case XHCI_EPCTX_0_EPSTATE_HALTED:
 3823                 err = xhci_cmd_reset_ep(sc, 0, epno, index);
 3824                 drop = (err != 0);
 3825                 if (drop)
 3826                         DPRINTF("Could not reset endpoint %u\n", epno);
 3827                 break;
 3828         default:
 3829                 drop = 1;
 3830                 err = xhci_cmd_stop_ep(sc, 0, epno, index);
 3831                 if (err != 0)
 3832                         DPRINTF("Could not stop endpoint %u\n", epno);
 3833                 break;
 3834         }
 3835 
 3836         err = xhci_cmd_set_tr_dequeue_ptr(sc,
 3837             (pepext->physaddr + (stream_id * sizeof(struct xhci_trb) *
 3838             XHCI_MAX_TRANSFERS)) | XHCI_EPCTX_2_DCS_SET(1),
 3839             stream_id, epno, index);
 3840 
 3841         if (err != 0)
 3842                 DPRINTF("Could not set dequeue ptr for endpoint %u\n", epno);
 3843 
 3844         /*
 3845          * Get the endpoint into the running state according to the
 3846          * endpoint context state diagram in the XHCI specification:
 3847          */
 3848 
 3849         mask = (1U << epno);
 3850 
 3851         /*
 3852          * So-called control and isochronous transfer types have
 3853          * predefined data toggles (USB 2.0) or sequence numbers (USB
 3854          * 3.0) and does not need to be dropped.
 3855          */
 3856         if (drop != 0 &&
 3857             (edesc->bmAttributes & UE_XFERTYPE) != UE_CONTROL &&
 3858             (edesc->bmAttributes & UE_XFERTYPE) != UE_ISOCHRONOUS) {
 3859                 /* drop endpoint context to reset data toggle value, if any. */
 3860                 xhci_configure_mask(udev, mask, 1);
 3861                 err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
 3862                 if (err != 0) {
 3863                         DPRINTF("Could not drop "
 3864                             "endpoint %u at slot %u.\n", epno, index);
 3865                 } else {
 3866                         sc->sc_hw.devs[index].ep_configured &= ~mask;
 3867                 }
 3868         }
 3869 
 3870         /*
 3871          * Always need to evaluate the slot context, because the maximum
 3872          * number of endpoint contexts is stored there.
 3873          */
 3874         xhci_configure_mask(udev, mask | 1U, 0);
 3875 
 3876         if (!(sc->sc_hw.devs[index].ep_configured & mask)) {
 3877                 err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
 3878                 if (err == 0)
 3879                         sc->sc_hw.devs[index].ep_configured |= mask;
 3880         } else {
 3881                 err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
 3882         }
 3883 
 3884         if (err != 0) {
 3885                 DPRINTF("Could not configure "
 3886                     "endpoint %u at slot %u.\n", epno, index);
 3887         }
 3888         XHCI_CMD_UNLOCK(sc);
 3889 
 3890         return (0);
 3891 }
 3892 
 3893 static void
 3894 xhci_xfer_unsetup(struct usb_xfer *xfer)
 3895 {
 3896         return;
 3897 }
 3898 
 3899 static void
 3900 xhci_start_dma_delay(struct usb_xfer *xfer)
 3901 {
 3902         struct xhci_softc *sc = XHCI_BUS2SC(xfer->xroot->bus);
 3903 
 3904         /* put transfer on interrupt queue (again) */
 3905         usbd_transfer_enqueue(&sc->sc_bus.intr_q, xfer);
 3906 
 3907         (void)usb_proc_msignal(USB_BUS_CONTROL_XFER_PROC(&sc->sc_bus),
 3908             &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
 3909 }
 3910 
 3911 static void
 3912 xhci_configure_msg(struct usb_proc_msg *pm)
 3913 {
 3914         struct xhci_softc *sc;
 3915         struct xhci_endpoint_ext *pepext;
 3916         struct usb_xfer *xfer;
 3917 
 3918         sc = XHCI_BUS2SC(((struct usb_bus_msg *)pm)->bus);
 3919 
 3920 restart:
 3921         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
 3922                 pepext = xhci_get_endpoint_ext(xfer->xroot->udev,
 3923                     xfer->endpoint->edesc);
 3924 
 3925                 if ((pepext->trb_halted != 0) ||
 3926                     (pepext->trb_running == 0)) {
 3927                         uint16_t i;
 3928 
 3929                         /* clear halted and running */
 3930                         pepext->trb_halted = 0;
 3931                         pepext->trb_running = 0;
 3932 
 3933                         /* nuke remaining buffered transfers */
 3934 
 3935                         for (i = 0; i != (XHCI_MAX_TRANSFERS *
 3936                             XHCI_MAX_STREAMS); i++) {
 3937                                 /*
 3938                                  * NOTE: We need to use the timeout
 3939                                  * error code here else existing
 3940                                  * isochronous clients can get
 3941                                  * confused:
 3942                                  */
 3943                                 if (pepext->xfer[i] != NULL) {
 3944                                         xhci_device_done(pepext->xfer[i],
 3945                                             USB_ERR_TIMEOUT);
 3946                                 }
 3947                         }
 3948 
 3949                         /*
 3950                          * NOTE: The USB transfer cannot vanish in
 3951                          * this state!
 3952                          */
 3953 
 3954                         USB_BUS_UNLOCK(&sc->sc_bus);
 3955 
 3956                         xhci_configure_reset_endpoint(xfer);
 3957 
 3958                         USB_BUS_LOCK(&sc->sc_bus);
 3959 
 3960                         /* check if halted is still cleared */
 3961                         if (pepext->trb_halted == 0) {
 3962                                 pepext->trb_running = 1;
 3963                                 memset(pepext->trb_index, 0,
 3964                                     sizeof(pepext->trb_index));
 3965                         }
 3966                         goto restart;
 3967                 }
 3968 
 3969                 if (xfer->flags_int.did_dma_delay) {
 3970                         /* remove transfer from interrupt queue (again) */
 3971                         usbd_transfer_dequeue(xfer);
 3972 
 3973                         /* we are finally done */
 3974                         usb_dma_delay_done_cb(xfer);
 3975 
 3976                         /* queue changed - restart */
 3977                         goto restart;
 3978                 }
 3979         }
 3980 
 3981         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
 3982                 /* try to insert xfer on HW queue */
 3983                 xhci_transfer_insert(xfer);
 3984 
 3985                 /* try to multi buffer */
 3986                 xhci_device_generic_multi_enter(xfer->endpoint,
 3987                     xfer->stream_id, NULL);
 3988         }
 3989 }
 3990 
 3991 static void
 3992 xhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
 3993     struct usb_endpoint *ep)
 3994 {
 3995         struct xhci_endpoint_ext *pepext;
 3996         struct xhci_softc *sc;
 3997         uint8_t index;
 3998         uint8_t epno;
 3999 
 4000         DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n",
 4001             ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode);
 4002 
 4003         if (udev->parent_hub == NULL) {
 4004                 /* root HUB has special endpoint handling */
 4005                 return;
 4006         }
 4007 
 4008         ep->methods = &xhci_device_generic_methods;
 4009 
 4010         pepext = xhci_get_endpoint_ext(udev, edesc);
 4011 
 4012         USB_BUS_LOCK(udev->bus);
 4013         pepext->trb_halted = 1;
 4014         pepext->trb_running = 0;
 4015 
 4016         /*
 4017          * When doing an alternate setting, except for control
 4018          * endpoints, we need to re-configure the XHCI endpoint
 4019          * context:
 4020          */
 4021         if ((edesc->bEndpointAddress & UE_ADDR) != 0) {
 4022                 sc = XHCI_BUS2SC(udev->bus);
 4023                 index = udev->controller_slot_id;
 4024                 epno = XHCI_EPNO2EPID(edesc->bEndpointAddress);
 4025                 sc->sc_hw.devs[index].ep_configured &= ~(1U << epno);
 4026         }
 4027         USB_BUS_UNLOCK(udev->bus);
 4028 }
 4029 
 4030 static void
 4031 xhci_ep_uninit(struct usb_device *udev, struct usb_endpoint *ep)
 4032 {
 4033         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4034         const struct usb_endpoint_descriptor *edesc = ep->edesc;
 4035         struct usb_page_search buf_inp;
 4036         struct usb_page_cache *pcinp;
 4037         uint32_t mask;
 4038         uint8_t index;
 4039         uint8_t epno;
 4040         usb_error_t err;
 4041 
 4042         if (udev->parent_hub == NULL) {
 4043                 /* root HUB has special endpoint handling */
 4044                 return;
 4045         }
 4046 
 4047         if ((edesc->bEndpointAddress & UE_ADDR) == 0) {
 4048                 /* control endpoint is never unconfigured */
 4049                 return;
 4050         }
 4051 
 4052         XHCI_CMD_LOCK(sc);
 4053         index = udev->controller_slot_id;
 4054         epno = XHCI_EPNO2EPID(edesc->bEndpointAddress);
 4055         mask = 1U << epno;
 4056 
 4057         if (sc->sc_hw.devs[index].ep_configured & mask) {
 4058                 USB_BUS_LOCK(udev->bus);
 4059                 xhci_configure_mask(udev, mask, 1);
 4060                 USB_BUS_UNLOCK(udev->bus);
 4061 
 4062                 pcinp = &sc->sc_hw.devs[index].input_pc;
 4063                 usbd_get_page(pcinp, 0, &buf_inp);
 4064                 err = xhci_cmd_configure_ep(sc, buf_inp.physaddr, 0, index);
 4065                 if (err) {
 4066                         DPRINTF("Unconfiguring endpoint failed: %d\n", err);
 4067                 } else {
 4068                         USB_BUS_LOCK(udev->bus);
 4069                         sc->sc_hw.devs[index].ep_configured &= ~mask;
 4070                         USB_BUS_UNLOCK(udev->bus);
 4071                 }
 4072         }
 4073         XHCI_CMD_UNLOCK(sc);
 4074 }
 4075 
 4076 static void
 4077 xhci_ep_clear_stall(struct usb_device *udev, struct usb_endpoint *ep)
 4078 {
 4079         struct xhci_endpoint_ext *pepext;
 4080 
 4081         DPRINTF("\n");
 4082 
 4083         if (udev->flags.usb_mode != USB_MODE_HOST) {
 4084                 /* not supported */
 4085                 return;
 4086         }
 4087         if (udev->parent_hub == NULL) {
 4088                 /* root HUB has special endpoint handling */
 4089                 return;
 4090         }
 4091 
 4092         pepext = xhci_get_endpoint_ext(udev, ep->edesc);
 4093 
 4094         USB_BUS_LOCK(udev->bus);
 4095         pepext->trb_halted = 1;
 4096         pepext->trb_running = 0;
 4097         USB_BUS_UNLOCK(udev->bus);
 4098 }
 4099 
 4100 static usb_error_t
 4101 xhci_device_init(struct usb_device *udev)
 4102 {
 4103         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4104         usb_error_t err;
 4105         uint8_t temp;
 4106 
 4107         /* no init for root HUB */
 4108         if (udev->parent_hub == NULL)
 4109                 return (0);
 4110 
 4111         XHCI_CMD_LOCK(sc);
 4112 
 4113         /* set invalid default */
 4114 
 4115         udev->controller_slot_id = sc->sc_noslot + 1;
 4116 
 4117         /* try to get a new slot ID from the XHCI */
 4118 
 4119         err = xhci_cmd_enable_slot(sc, &temp);
 4120 
 4121         if (err) {
 4122                 XHCI_CMD_UNLOCK(sc);
 4123                 return (err);
 4124         }
 4125 
 4126         if (temp > sc->sc_noslot) {
 4127                 XHCI_CMD_UNLOCK(sc);
 4128                 return (USB_ERR_BAD_ADDRESS);
 4129         }
 4130 
 4131         if (sc->sc_hw.devs[temp].state != XHCI_ST_DISABLED) {
 4132                 DPRINTF("slot %u already allocated.\n", temp);
 4133                 XHCI_CMD_UNLOCK(sc);
 4134                 return (USB_ERR_BAD_ADDRESS);
 4135         }
 4136 
 4137         /* store slot ID for later reference */
 4138 
 4139         udev->controller_slot_id = temp;
 4140 
 4141         /* reset data structure */
 4142 
 4143         memset(&sc->sc_hw.devs[temp], 0, sizeof(sc->sc_hw.devs[0]));
 4144 
 4145         /* set mark slot allocated */
 4146 
 4147         sc->sc_hw.devs[temp].state = XHCI_ST_ENABLED;
 4148 
 4149         err = xhci_alloc_device_ext(udev);
 4150 
 4151         XHCI_CMD_UNLOCK(sc);
 4152 
 4153         /* get device into default state */
 4154 
 4155         if (err == 0)
 4156                 err = xhci_set_address(udev, NULL, 0);
 4157 
 4158         return (err);
 4159 }
 4160 
 4161 static void
 4162 xhci_device_uninit(struct usb_device *udev)
 4163 {
 4164         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4165         uint8_t index;
 4166 
 4167         /* no init for root HUB */
 4168         if (udev->parent_hub == NULL)
 4169                 return;
 4170 
 4171         XHCI_CMD_LOCK(sc);
 4172 
 4173         index = udev->controller_slot_id;
 4174 
 4175         if (index <= sc->sc_noslot) {
 4176                 xhci_cmd_disable_slot(sc, index);
 4177                 sc->sc_hw.devs[index].state = XHCI_ST_DISABLED;
 4178 
 4179                 /* free device extension */
 4180                 xhci_free_device_ext(udev);
 4181         }
 4182 
 4183         XHCI_CMD_UNLOCK(sc);
 4184 }
 4185 
 4186 static void
 4187 xhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
 4188 {
 4189         /*
 4190          * Wait until the hardware has finished any possible use of
 4191          * the transfer descriptor(s)
 4192          */
 4193         *pus = 2048;                    /* microseconds */
 4194 }
 4195 
 4196 static void
 4197 xhci_device_resume(struct usb_device *udev)
 4198 {
 4199         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4200         uint8_t index;
 4201         uint8_t n;
 4202         uint8_t p;
 4203 
 4204         DPRINTF("\n");
 4205 
 4206         /* check for root HUB */
 4207         if (udev->parent_hub == NULL)
 4208                 return;
 4209 
 4210         index = udev->controller_slot_id;
 4211 
 4212         XHCI_CMD_LOCK(sc);
 4213 
 4214         /* blindly resume all endpoints */
 4215 
 4216         USB_BUS_LOCK(udev->bus);
 4217 
 4218         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
 4219                 for (p = 0; p != XHCI_MAX_STREAMS; p++) {
 4220                         XWRITE4(sc, door, XHCI_DOORBELL(index),
 4221                             n | XHCI_DB_SID_SET(p));
 4222                 }
 4223         }
 4224 
 4225         USB_BUS_UNLOCK(udev->bus);
 4226 
 4227         XHCI_CMD_UNLOCK(sc);
 4228 }
 4229 
 4230 static void
 4231 xhci_device_suspend(struct usb_device *udev)
 4232 {
 4233         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4234         uint8_t index;
 4235         uint8_t n;
 4236         usb_error_t err;
 4237 
 4238         DPRINTF("\n");
 4239 
 4240         /* check for root HUB */
 4241         if (udev->parent_hub == NULL)
 4242                 return;
 4243 
 4244         index = udev->controller_slot_id;
 4245 
 4246         XHCI_CMD_LOCK(sc);
 4247 
 4248         /* blindly suspend all endpoints */
 4249 
 4250         for (n = 1; n != XHCI_MAX_ENDPOINTS; n++) {
 4251                 err = xhci_cmd_stop_ep(sc, 1, n, index);
 4252                 if (err != 0) {
 4253                         DPRINTF("Failed to suspend endpoint "
 4254                             "%u on slot %u (ignored).\n", n, index);
 4255                 }
 4256         }
 4257 
 4258         XHCI_CMD_UNLOCK(sc);
 4259 }
 4260 
 4261 static void
 4262 xhci_set_hw_power(struct usb_bus *bus)
 4263 {
 4264         DPRINTF("\n");
 4265 }
 4266 
 4267 static void
 4268 xhci_device_state_change(struct usb_device *udev)
 4269 {
 4270         struct xhci_softc *sc = XHCI_BUS2SC(udev->bus);
 4271         struct usb_page_search buf_inp;
 4272         usb_error_t err;
 4273         uint8_t index;
 4274 
 4275         /* check for root HUB */
 4276         if (udev->parent_hub == NULL)
 4277                 return;
 4278 
 4279         index = udev->controller_slot_id;
 4280 
 4281         DPRINTF("\n");
 4282 
 4283         if (usb_get_device_state(udev) == USB_STATE_CONFIGURED) {
 4284                 err = uhub_query_info(udev, &sc->sc_hw.devs[index].nports, 
 4285                     &sc->sc_hw.devs[index].tt);
 4286                 if (err != 0)
 4287                         sc->sc_hw.devs[index].nports = 0;
 4288         }
 4289 
 4290         XHCI_CMD_LOCK(sc);
 4291 
 4292         switch (usb_get_device_state(udev)) {
 4293         case USB_STATE_POWERED:
 4294                 if (sc->sc_hw.devs[index].state == XHCI_ST_DEFAULT)
 4295                         break;
 4296 
 4297                 /* set default state */
 4298                 sc->sc_hw.devs[index].state = XHCI_ST_DEFAULT;
 4299                 sc->sc_hw.devs[index].ep_configured = 3U;
 4300 
 4301                 /* reset number of contexts */
 4302                 sc->sc_hw.devs[index].context_num = 0;
 4303 
 4304                 err = xhci_cmd_reset_dev(sc, index);
 4305 
 4306                 if (err != 0) {
 4307                         DPRINTF("Device reset failed "
 4308                             "for slot %u.\n", index);
 4309                 }
 4310                 break;
 4311 
 4312         case USB_STATE_ADDRESSED:
 4313                 if (sc->sc_hw.devs[index].state == XHCI_ST_ADDRESSED)
 4314                         break;
 4315 
 4316                 sc->sc_hw.devs[index].state = XHCI_ST_ADDRESSED;
 4317                 sc->sc_hw.devs[index].ep_configured = 3U;
 4318 
 4319                 /* set configure mask to slot only */
 4320                 xhci_configure_mask(udev, 1, 0);
 4321 
 4322                 /* deconfigure all endpoints, except EP0 */
 4323                 err = xhci_cmd_configure_ep(sc, 0, 1, index);
 4324 
 4325                 if (err) {
 4326                         DPRINTF("Failed to deconfigure "
 4327                             "slot %u.\n", index);
 4328                 }
 4329                 break;
 4330 
 4331         case USB_STATE_CONFIGURED:
 4332                 if (sc->sc_hw.devs[index].state == XHCI_ST_CONFIGURED) {
 4333                         /* deconfigure all endpoints, except EP0 */
 4334                         err = xhci_cmd_configure_ep(sc, 0, 1, index);
 4335 
 4336                         if (err) {
 4337                                 DPRINTF("Failed to deconfigure "
 4338                                     "slot %u.\n", index);
 4339                         }
 4340                 }
 4341 
 4342                 /* set configured state */
 4343                 sc->sc_hw.devs[index].state = XHCI_ST_CONFIGURED;
 4344                 sc->sc_hw.devs[index].ep_configured = 3U;
 4345 
 4346                 /* reset number of contexts */
 4347                 sc->sc_hw.devs[index].context_num = 0;
 4348 
 4349                 usbd_get_page(&sc->sc_hw.devs[index].input_pc, 0, &buf_inp);
 4350 
 4351                 xhci_configure_mask(udev, 3, 0);
 4352 
 4353                 err = xhci_configure_device(udev);
 4354                 if (err != 0) {
 4355                         DPRINTF("Could not configure device "
 4356                             "at slot %u.\n", index);
 4357                 }
 4358 
 4359                 err = xhci_cmd_evaluate_ctx(sc, buf_inp.physaddr, index);
 4360                 if (err != 0) {
 4361                         DPRINTF("Could not evaluate device "
 4362                             "context at slot %u.\n", index);
 4363                 }
 4364                 break;
 4365 
 4366         default:
 4367                 break;
 4368         }
 4369         XHCI_CMD_UNLOCK(sc);
 4370 }
 4371 
 4372 static usb_error_t
 4373 xhci_set_endpoint_mode(struct usb_device *udev, struct usb_endpoint *ep,
 4374     uint8_t ep_mode)
 4375 {
 4376         switch (ep_mode) {
 4377         case USB_EP_MODE_DEFAULT:
 4378                 return (0);
 4379         case USB_EP_MODE_STREAMS:
 4380                 if (xhcistreams == 0 || 
 4381                     (ep->edesc->bmAttributes & UE_XFERTYPE) != UE_BULK ||
 4382                     udev->speed != USB_SPEED_SUPER)
 4383                         return (USB_ERR_INVAL);
 4384                 return (0);
 4385         default:
 4386                 return (USB_ERR_INVAL);
 4387         }
 4388 }
 4389 
 4390 static const struct usb_bus_methods xhci_bus_methods = {
 4391         .endpoint_init = xhci_ep_init,
 4392         .endpoint_uninit = xhci_ep_uninit,
 4393         .xfer_setup = xhci_xfer_setup,
 4394         .xfer_unsetup = xhci_xfer_unsetup,
 4395         .get_dma_delay = xhci_get_dma_delay,
 4396         .device_init = xhci_device_init,
 4397         .device_uninit = xhci_device_uninit,
 4398         .device_resume = xhci_device_resume,
 4399         .device_suspend = xhci_device_suspend,
 4400         .set_hw_power = xhci_set_hw_power,
 4401         .roothub_exec = xhci_roothub_exec,
 4402         .xfer_poll = xhci_do_poll,
 4403         .start_dma_delay = xhci_start_dma_delay,
 4404         .set_address = xhci_set_address,
 4405         .clear_stall = xhci_ep_clear_stall,
 4406         .device_state_change = xhci_device_state_change,
 4407         .set_hw_power_sleep = xhci_set_hw_power_sleep,
 4408         .set_endpoint_mode = xhci_set_endpoint_mode,
 4409 };

Cache object: 08aa7a1f6f959b3421bde17447086259


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.