qemu/hw/usb/hcd-ehci.c
<<
>>
Prefs
   1/*
   2 * QEMU USB EHCI Emulation
   3 *
   4 * Copyright(c) 2008  Emutex Ltd. (address@hidden)
   5 * Copyright(c) 2011-2012 Red Hat, Inc.
   6 *
   7 * Red Hat Authors:
   8 * Gerd Hoffmann <kraxel@redhat.com>
   9 * Hans de Goede <hdegoede@redhat.com>
  10 *
  11 * EHCI project was started by Mark Burkley, with contributions by
  12 * Niels de Vos.  David S. Ahern continued working on it.  Kevin Wolf,
  13 * Jan Kiszka and Vincent Palatin contributed bugfixes.
  14 *
  15 *
  16 * This library is free software; you can redistribute it and/or
  17 * modify it under the terms of the GNU Lesser General Public
  18 * License as published by the Free Software Foundation; either
  19 * version 2 of the License, or(at your option) any later version.
  20 *
  21 * This library is distributed in the hope that it will be useful,
  22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  24 * Lesser General Public License for more details.
  25 *
  26 * You should have received a copy of the GNU General Public License
  27 * along with this program; if not, see <http://www.gnu.org/licenses/>.
  28 */
  29
  30#include "hw/usb/ehci-regs.h"
  31#include "hw/usb/hcd-ehci.h"
  32#include "trace.h"
  33
  34#define FRAME_TIMER_FREQ 1000
  35#define FRAME_TIMER_NS   (1000000000 / FRAME_TIMER_FREQ)
  36#define UFRAME_TIMER_NS  (FRAME_TIMER_NS / 8)
  37
  38#define NB_MAXINTRATE    8        // Max rate at which controller issues ints
  39#define BUFF_SIZE        5*4096   // Max bytes to transfer per transaction
  40#define MAX_QH           100      // Max allowable queue heads in a chain
  41#define MIN_UFR_PER_TICK 24       /* Min frames to process when catching up */
  42#define PERIODIC_ACTIVE  512      /* Micro-frames */
  43
  44/*  Internal periodic / asynchronous schedule state machine states
  45 */
  46typedef enum {
  47    EST_INACTIVE = 1000,
  48    EST_ACTIVE,
  49    EST_EXECUTING,
  50    EST_SLEEPING,
  51    /*  The following states are internal to the state machine function
  52    */
  53    EST_WAITLISTHEAD,
  54    EST_FETCHENTRY,
  55    EST_FETCHQH,
  56    EST_FETCHITD,
  57    EST_FETCHSITD,
  58    EST_ADVANCEQUEUE,
  59    EST_FETCHQTD,
  60    EST_EXECUTE,
  61    EST_WRITEBACK,
  62    EST_HORIZONTALQH
  63} EHCI_STATES;
  64
  65/* macros for accessing fields within next link pointer entry */
  66#define NLPTR_GET(x)             ((x) & 0xffffffe0)
  67#define NLPTR_TYPE_GET(x)        (((x) >> 1) & 3)
  68#define NLPTR_TBIT(x)            ((x) & 1)  // 1=invalid, 0=valid
  69
  70/* link pointer types */
  71#define NLPTR_TYPE_ITD           0     // isoc xfer descriptor
  72#define NLPTR_TYPE_QH            1     // queue head
  73#define NLPTR_TYPE_STITD         2     // split xaction, isoc xfer descriptor
  74#define NLPTR_TYPE_FSTN          3     // frame span traversal node
  75
  76#define SET_LAST_RUN_CLOCK(s) \
  77    (s)->last_run_ns = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
  78
  79/* nifty macros from Arnon's EHCI version  */
  80#define get_field(data, field) \
  81    (((data) & field##_MASK) >> field##_SH)
  82
  83#define set_field(data, newval, field) do { \
  84    uint32_t val = *data; \
  85    val &= ~ field##_MASK; \
  86    val |= ((newval) << field##_SH) & field##_MASK; \
  87    *data = val; \
  88    } while(0)
  89
  90static const char *ehci_state_names[] = {
  91    [EST_INACTIVE]     = "INACTIVE",
  92    [EST_ACTIVE]       = "ACTIVE",
  93    [EST_EXECUTING]    = "EXECUTING",
  94    [EST_SLEEPING]     = "SLEEPING",
  95    [EST_WAITLISTHEAD] = "WAITLISTHEAD",
  96    [EST_FETCHENTRY]   = "FETCH ENTRY",
  97    [EST_FETCHQH]      = "FETCH QH",
  98    [EST_FETCHITD]     = "FETCH ITD",
  99    [EST_ADVANCEQUEUE] = "ADVANCEQUEUE",
 100    [EST_FETCHQTD]     = "FETCH QTD",
 101    [EST_EXECUTE]      = "EXECUTE",
 102    [EST_WRITEBACK]    = "WRITEBACK",
 103    [EST_HORIZONTALQH] = "HORIZONTALQH",
 104};
 105
 106static const char *ehci_mmio_names[] = {
 107    [USBCMD]            = "USBCMD",
 108    [USBSTS]            = "USBSTS",
 109    [USBINTR]           = "USBINTR",
 110    [FRINDEX]           = "FRINDEX",
 111    [PERIODICLISTBASE]  = "P-LIST BASE",
 112    [ASYNCLISTADDR]     = "A-LIST ADDR",
 113    [CONFIGFLAG]        = "CONFIGFLAG",
 114};
 115
 116static int ehci_state_executing(EHCIQueue *q);
 117static int ehci_state_writeback(EHCIQueue *q);
 118static int ehci_state_advqueue(EHCIQueue *q);
 119static int ehci_fill_queue(EHCIPacket *p);
 120static void ehci_free_packet(EHCIPacket *p);
 121
 122static const char *nr2str(const char **n, size_t len, uint32_t nr)
 123{
 124    if (nr < len && n[nr] != NULL) {
 125        return n[nr];
 126    } else {
 127        return "unknown";
 128    }
 129}
 130
 131static const char *state2str(uint32_t state)
 132{
 133    return nr2str(ehci_state_names, ARRAY_SIZE(ehci_state_names), state);
 134}
 135
 136static const char *addr2str(hwaddr addr)
 137{
 138    return nr2str(ehci_mmio_names, ARRAY_SIZE(ehci_mmio_names), addr);
 139}
 140
 141static void ehci_trace_usbsts(uint32_t mask, int state)
 142{
 143    /* interrupts */
 144    if (mask & USBSTS_INT) {
 145        trace_usb_ehci_usbsts("INT", state);
 146    }
 147    if (mask & USBSTS_ERRINT) {
 148        trace_usb_ehci_usbsts("ERRINT", state);
 149    }
 150    if (mask & USBSTS_PCD) {
 151        trace_usb_ehci_usbsts("PCD", state);
 152    }
 153    if (mask & USBSTS_FLR) {
 154        trace_usb_ehci_usbsts("FLR", state);
 155    }
 156    if (mask & USBSTS_HSE) {
 157        trace_usb_ehci_usbsts("HSE", state);
 158    }
 159    if (mask & USBSTS_IAA) {
 160        trace_usb_ehci_usbsts("IAA", state);
 161    }
 162
 163    /* status */
 164    if (mask & USBSTS_HALT) {
 165        trace_usb_ehci_usbsts("HALT", state);
 166    }
 167    if (mask & USBSTS_REC) {
 168        trace_usb_ehci_usbsts("REC", state);
 169    }
 170    if (mask & USBSTS_PSS) {
 171        trace_usb_ehci_usbsts("PSS", state);
 172    }
 173    if (mask & USBSTS_ASS) {
 174        trace_usb_ehci_usbsts("ASS", state);
 175    }
 176}
 177
 178static inline void ehci_set_usbsts(EHCIState *s, int mask)
 179{
 180    if ((s->usbsts & mask) == mask) {
 181        return;
 182    }
 183    ehci_trace_usbsts(mask, 1);
 184    s->usbsts |= mask;
 185}
 186
 187static inline void ehci_clear_usbsts(EHCIState *s, int mask)
 188{
 189    if ((s->usbsts & mask) == 0) {
 190        return;
 191    }
 192    ehci_trace_usbsts(mask, 0);
 193    s->usbsts &= ~mask;
 194}
 195
 196/* update irq line */
 197static inline void ehci_update_irq(EHCIState *s)
 198{
 199    int level = 0;
 200
 201    if ((s->usbsts & USBINTR_MASK) & s->usbintr) {
 202        level = 1;
 203    }
 204
 205    trace_usb_ehci_irq(level, s->frindex, s->usbsts, s->usbintr);
 206    qemu_set_irq(s->irq, level);
 207}
 208
 209/* flag interrupt condition */
 210static inline void ehci_raise_irq(EHCIState *s, int intr)
 211{
 212    if (intr & (USBSTS_PCD | USBSTS_FLR | USBSTS_HSE)) {
 213        s->usbsts |= intr;
 214        ehci_update_irq(s);
 215    } else {
 216        s->usbsts_pending |= intr;
 217    }
 218}
 219
 220/*
 221 * Commit pending interrupts (added via ehci_raise_irq),
 222 * at the rate allowed by "Interrupt Threshold Control".
 223 */
 224static inline void ehci_commit_irq(EHCIState *s)
 225{
 226    uint32_t itc;
 227
 228    if (!s->usbsts_pending) {
 229        return;
 230    }
 231    if (s->usbsts_frindex > s->frindex) {
 232        return;
 233    }
 234
 235    itc = (s->usbcmd >> 16) & 0xff;
 236    s->usbsts |= s->usbsts_pending;
 237    s->usbsts_pending = 0;
 238    s->usbsts_frindex = s->frindex + itc;
 239    ehci_update_irq(s);
 240}
 241
 242static void ehci_update_halt(EHCIState *s)
 243{
 244    if (s->usbcmd & USBCMD_RUNSTOP) {
 245        ehci_clear_usbsts(s, USBSTS_HALT);
 246    } else {
 247        if (s->astate == EST_INACTIVE && s->pstate == EST_INACTIVE) {
 248            ehci_set_usbsts(s, USBSTS_HALT);
 249        }
 250    }
 251}
 252
 253static void ehci_set_state(EHCIState *s, int async, int state)
 254{
 255    if (async) {
 256        trace_usb_ehci_state("async", state2str(state));
 257        s->astate = state;
 258        if (s->astate == EST_INACTIVE) {
 259            ehci_clear_usbsts(s, USBSTS_ASS);
 260            ehci_update_halt(s);
 261        } else {
 262            ehci_set_usbsts(s, USBSTS_ASS);
 263        }
 264    } else {
 265        trace_usb_ehci_state("periodic", state2str(state));
 266        s->pstate = state;
 267        if (s->pstate == EST_INACTIVE) {
 268            ehci_clear_usbsts(s, USBSTS_PSS);
 269            ehci_update_halt(s);
 270        } else {
 271            ehci_set_usbsts(s, USBSTS_PSS);
 272        }
 273    }
 274}
 275
 276static int ehci_get_state(EHCIState *s, int async)
 277{
 278    return async ? s->astate : s->pstate;
 279}
 280
 281static void ehci_set_fetch_addr(EHCIState *s, int async, uint32_t addr)
 282{
 283    if (async) {
 284        s->a_fetch_addr = addr;
 285    } else {
 286        s->p_fetch_addr = addr;
 287    }
 288}
 289
 290static int ehci_get_fetch_addr(EHCIState *s, int async)
 291{
 292    return async ? s->a_fetch_addr : s->p_fetch_addr;
 293}
 294
 295static void ehci_trace_qh(EHCIQueue *q, hwaddr addr, EHCIqh *qh)
 296{
 297    /* need three here due to argument count limits */
 298    trace_usb_ehci_qh_ptrs(q, addr, qh->next,
 299                           qh->current_qtd, qh->next_qtd, qh->altnext_qtd);
 300    trace_usb_ehci_qh_fields(addr,
 301                             get_field(qh->epchar, QH_EPCHAR_RL),
 302                             get_field(qh->epchar, QH_EPCHAR_MPLEN),
 303                             get_field(qh->epchar, QH_EPCHAR_EPS),
 304                             get_field(qh->epchar, QH_EPCHAR_EP),
 305                             get_field(qh->epchar, QH_EPCHAR_DEVADDR));
 306    trace_usb_ehci_qh_bits(addr,
 307                           (bool)(qh->epchar & QH_EPCHAR_C),
 308                           (bool)(qh->epchar & QH_EPCHAR_H),
 309                           (bool)(qh->epchar & QH_EPCHAR_DTC),
 310                           (bool)(qh->epchar & QH_EPCHAR_I));
 311}
 312
 313static void ehci_trace_qtd(EHCIQueue *q, hwaddr addr, EHCIqtd *qtd)
 314{
 315    /* need three here due to argument count limits */
 316    trace_usb_ehci_qtd_ptrs(q, addr, qtd->next, qtd->altnext);
 317    trace_usb_ehci_qtd_fields(addr,
 318                              get_field(qtd->token, QTD_TOKEN_TBYTES),
 319                              get_field(qtd->token, QTD_TOKEN_CPAGE),
 320                              get_field(qtd->token, QTD_TOKEN_CERR),
 321                              get_field(qtd->token, QTD_TOKEN_PID));
 322    trace_usb_ehci_qtd_bits(addr,
 323                            (bool)(qtd->token & QTD_TOKEN_IOC),
 324                            (bool)(qtd->token & QTD_TOKEN_ACTIVE),
 325                            (bool)(qtd->token & QTD_TOKEN_HALT),
 326                            (bool)(qtd->token & QTD_TOKEN_BABBLE),
 327                            (bool)(qtd->token & QTD_TOKEN_XACTERR));
 328}
 329
 330static void ehci_trace_itd(EHCIState *s, hwaddr addr, EHCIitd *itd)
 331{
 332    trace_usb_ehci_itd(addr, itd->next,
 333                       get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT),
 334                       get_field(itd->bufptr[2], ITD_BUFPTR_MULT),
 335                       get_field(itd->bufptr[0], ITD_BUFPTR_EP),
 336                       get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR));
 337}
 338
 339static void ehci_trace_sitd(EHCIState *s, hwaddr addr,
 340                            EHCIsitd *sitd)
 341{
 342    trace_usb_ehci_sitd(addr, sitd->next,
 343                        (bool)(sitd->results & SITD_RESULTS_ACTIVE));
 344}
 345
 346static void ehci_trace_guest_bug(EHCIState *s, const char *message)
 347{
 348    trace_usb_ehci_guest_bug(message);
 349    fprintf(stderr, "ehci warning: %s\n", message);
 350}
 351
 352static inline bool ehci_enabled(EHCIState *s)
 353{
 354    return s->usbcmd & USBCMD_RUNSTOP;
 355}
 356
 357static inline bool ehci_async_enabled(EHCIState *s)
 358{
 359    return ehci_enabled(s) && (s->usbcmd & USBCMD_ASE);
 360}
 361
 362static inline bool ehci_periodic_enabled(EHCIState *s)
 363{
 364    return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
 365}
 366
 367/* Get an array of dwords from main memory */
 368static inline int get_dwords(EHCIState *ehci, uint32_t addr,
 369                             uint32_t *buf, int num)
 370{
 371    int i;
 372
 373    if (!ehci->as) {
 374        ehci_raise_irq(ehci, USBSTS_HSE);
 375        ehci->usbcmd &= ~USBCMD_RUNSTOP;
 376        trace_usb_ehci_dma_error();
 377        return -1;
 378    }
 379
 380    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 381        dma_memory_read(ehci->as, addr, buf, sizeof(*buf));
 382        *buf = le32_to_cpu(*buf);
 383    }
 384
 385    return num;
 386}
 387
 388/* Put an array of dwords in to main memory */
 389static inline int put_dwords(EHCIState *ehci, uint32_t addr,
 390                             uint32_t *buf, int num)
 391{
 392    int i;
 393
 394    if (!ehci->as) {
 395        ehci_raise_irq(ehci, USBSTS_HSE);
 396        ehci->usbcmd &= ~USBCMD_RUNSTOP;
 397        trace_usb_ehci_dma_error();
 398        return -1;
 399    }
 400
 401    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 402        uint32_t tmp = cpu_to_le32(*buf);
 403        dma_memory_write(ehci->as, addr, &tmp, sizeof(tmp));
 404    }
 405
 406    return num;
 407}
 408
 409static int ehci_get_pid(EHCIqtd *qtd)
 410{
 411    switch (get_field(qtd->token, QTD_TOKEN_PID)) {
 412    case 0:
 413        return USB_TOKEN_OUT;
 414    case 1:
 415        return USB_TOKEN_IN;
 416    case 2:
 417        return USB_TOKEN_SETUP;
 418    default:
 419        fprintf(stderr, "bad token\n");
 420        return 0;
 421    }
 422}
 423
 424static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
 425{
 426    uint32_t devaddr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
 427    uint32_t endp    = get_field(qh->epchar, QH_EPCHAR_EP);
 428    if ((devaddr != get_field(q->qh.epchar, QH_EPCHAR_DEVADDR)) ||
 429        (endp    != get_field(q->qh.epchar, QH_EPCHAR_EP)) ||
 430        (qh->current_qtd != q->qh.current_qtd) ||
 431        (q->async && qh->next_qtd != q->qh.next_qtd) ||
 432        (memcmp(&qh->altnext_qtd, &q->qh.altnext_qtd,
 433                                 7 * sizeof(uint32_t)) != 0) ||
 434        (q->dev != NULL && q->dev->addr != devaddr)) {
 435        return false;
 436    } else {
 437        return true;
 438    }
 439}
 440
 441static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
 442{
 443    if (p->qtdaddr != p->queue->qtdaddr ||
 444        (p->queue->async && !NLPTR_TBIT(p->qtd.next) &&
 445            (p->qtd.next != qtd->next)) ||
 446        (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd->altnext)) ||
 447        p->qtd.token != qtd->token ||
 448        p->qtd.bufptr[0] != qtd->bufptr[0]) {
 449        return false;
 450    } else {
 451        return true;
 452    }
 453}
 454
 455static bool ehci_verify_pid(EHCIQueue *q, EHCIqtd *qtd)
 456{
 457    int ep  = get_field(q->qh.epchar, QH_EPCHAR_EP);
 458    int pid = ehci_get_pid(qtd);
 459
 460    /* Note the pid changing is normal for ep 0 (the control ep) */
 461    if (q->last_pid && ep != 0 && pid != q->last_pid) {
 462        return false;
 463    } else {
 464        return true;
 465    }
 466}
 467
 468/* Finish executing and writeback a packet outside of the regular
 469   fetchqh -> fetchqtd -> execute -> writeback cycle */
 470static void ehci_writeback_async_complete_packet(EHCIPacket *p)
 471{
 472    EHCIQueue *q = p->queue;
 473    EHCIqtd qtd;
 474    EHCIqh qh;
 475    int state;
 476
 477    /* Verify the qh + qtd, like we do when going through fetchqh & fetchqtd */
 478    get_dwords(q->ehci, NLPTR_GET(q->qhaddr),
 479               (uint32_t *) &qh, sizeof(EHCIqh) >> 2);
 480    get_dwords(q->ehci, NLPTR_GET(q->qtdaddr),
 481               (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2);
 482    if (!ehci_verify_qh(q, &qh) || !ehci_verify_qtd(p, &qtd)) {
 483        p->async = EHCI_ASYNC_INITIALIZED;
 484        ehci_free_packet(p);
 485        return;
 486    }
 487
 488    state = ehci_get_state(q->ehci, q->async);
 489    ehci_state_executing(q);
 490    ehci_state_writeback(q); /* Frees the packet! */
 491    if (!(q->qh.token & QTD_TOKEN_HALT)) {
 492        ehci_state_advqueue(q);
 493    }
 494    ehci_set_state(q->ehci, q->async, state);
 495}
 496
 497/* packet management */
 498
 499static EHCIPacket *ehci_alloc_packet(EHCIQueue *q)
 500{
 501    EHCIPacket *p;
 502
 503    p = g_new0(EHCIPacket, 1);
 504    p->queue = q;
 505    usb_packet_init(&p->packet);
 506    QTAILQ_INSERT_TAIL(&q->packets, p, next);
 507    trace_usb_ehci_packet_action(p->queue, p, "alloc");
 508    return p;
 509}
 510
 511static void ehci_free_packet(EHCIPacket *p)
 512{
 513    if (p->async == EHCI_ASYNC_FINISHED &&
 514            !(p->queue->qh.token & QTD_TOKEN_HALT)) {
 515        ehci_writeback_async_complete_packet(p);
 516        return;
 517    }
 518    trace_usb_ehci_packet_action(p->queue, p, "free");
 519    if (p->async == EHCI_ASYNC_INFLIGHT) {
 520        usb_cancel_packet(&p->packet);
 521    }
 522    if (p->async == EHCI_ASYNC_FINISHED &&
 523            p->packet.status == USB_RET_SUCCESS) {
 524        fprintf(stderr,
 525                "EHCI: Dropping completed packet from halted %s ep %02X\n",
 526                (p->pid == USB_TOKEN_IN) ? "in" : "out",
 527                get_field(p->queue->qh.epchar, QH_EPCHAR_EP));
 528    }
 529    if (p->async != EHCI_ASYNC_NONE) {
 530        usb_packet_unmap(&p->packet, &p->sgl);
 531        qemu_sglist_destroy(&p->sgl);
 532    }
 533    QTAILQ_REMOVE(&p->queue->packets, p, next);
 534    usb_packet_cleanup(&p->packet);
 535    g_free(p);
 536}
 537
 538/* queue management */
 539
 540static EHCIQueue *ehci_alloc_queue(EHCIState *ehci, uint32_t addr, int async)
 541{
 542    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 543    EHCIQueue *q;
 544
 545    q = g_malloc0(sizeof(*q));
 546    q->ehci = ehci;
 547    q->qhaddr = addr;
 548    q->async = async;
 549    QTAILQ_INIT(&q->packets);
 550    QTAILQ_INSERT_HEAD(head, q, next);
 551    trace_usb_ehci_queue_action(q, "alloc");
 552    return q;
 553}
 554
 555static void ehci_queue_stopped(EHCIQueue *q)
 556{
 557    int endp  = get_field(q->qh.epchar, QH_EPCHAR_EP);
 558
 559    if (!q->last_pid || !q->dev) {
 560        return;
 561    }
 562
 563    usb_device_ep_stopped(q->dev, usb_ep_get(q->dev, q->last_pid, endp));
 564}
 565
 566static int ehci_cancel_queue(EHCIQueue *q)
 567{
 568    EHCIPacket *p;
 569    int packets = 0;
 570
 571    p = QTAILQ_FIRST(&q->packets);
 572    if (p == NULL) {
 573        goto leave;
 574    }
 575
 576    trace_usb_ehci_queue_action(q, "cancel");
 577    do {
 578        ehci_free_packet(p);
 579        packets++;
 580    } while ((p = QTAILQ_FIRST(&q->packets)) != NULL);
 581
 582leave:
 583    ehci_queue_stopped(q);
 584    return packets;
 585}
 586
 587static int ehci_reset_queue(EHCIQueue *q)
 588{
 589    int packets;
 590
 591    trace_usb_ehci_queue_action(q, "reset");
 592    packets = ehci_cancel_queue(q);
 593    q->dev = NULL;
 594    q->qtdaddr = 0;
 595    q->last_pid = 0;
 596    return packets;
 597}
 598
 599static void ehci_free_queue(EHCIQueue *q, const char *warn)
 600{
 601    EHCIQueueHead *head = q->async ? &q->ehci->aqueues : &q->ehci->pqueues;
 602    int cancelled;
 603
 604    trace_usb_ehci_queue_action(q, "free");
 605    cancelled = ehci_cancel_queue(q);
 606    if (warn && cancelled > 0) {
 607        ehci_trace_guest_bug(q->ehci, warn);
 608    }
 609    QTAILQ_REMOVE(head, q, next);
 610    g_free(q);
 611}
 612
 613static EHCIQueue *ehci_find_queue_by_qh(EHCIState *ehci, uint32_t addr,
 614                                        int async)
 615{
 616    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 617    EHCIQueue *q;
 618
 619    QTAILQ_FOREACH(q, head, next) {
 620        if (addr == q->qhaddr) {
 621            return q;
 622        }
 623    }
 624    return NULL;
 625}
 626
 627static void ehci_queues_rip_unused(EHCIState *ehci, int async)
 628{
 629    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 630    const char *warn = async ? "guest unlinked busy QH" : NULL;
 631    uint64_t maxage = FRAME_TIMER_NS * ehci->maxframes * 4;
 632    EHCIQueue *q, *tmp;
 633
 634    QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
 635        if (q->seen) {
 636            q->seen = 0;
 637            q->ts = ehci->last_run_ns;
 638            continue;
 639        }
 640        if (ehci->last_run_ns < q->ts + maxage) {
 641            continue;
 642        }
 643        ehci_free_queue(q, warn);
 644    }
 645}
 646
 647static void ehci_queues_rip_unseen(EHCIState *ehci, int async)
 648{
 649    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 650    EHCIQueue *q, *tmp;
 651
 652    QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
 653        if (!q->seen) {
 654            ehci_free_queue(q, NULL);
 655        }
 656    }
 657}
 658
 659static void ehci_queues_rip_device(EHCIState *ehci, USBDevice *dev, int async)
 660{
 661    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 662    EHCIQueue *q, *tmp;
 663
 664    QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
 665        if (q->dev != dev) {
 666            continue;
 667        }
 668        ehci_free_queue(q, NULL);
 669    }
 670}
 671
 672static void ehci_queues_rip_all(EHCIState *ehci, int async)
 673{
 674    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
 675    const char *warn = async ? "guest stopped busy async schedule" : NULL;
 676    EHCIQueue *q, *tmp;
 677
 678    QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
 679        ehci_free_queue(q, warn);
 680    }
 681}
 682
 683/* Attach or detach a device on root hub */
 684
 685static void ehci_attach(USBPort *port)
 686{
 687    EHCIState *s = port->opaque;
 688    uint32_t *portsc = &s->portsc[port->index];
 689    const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
 690
 691    trace_usb_ehci_port_attach(port->index, owner, port->dev->product_desc);
 692
 693    if (*portsc & PORTSC_POWNER) {
 694        USBPort *companion = s->companion_ports[port->index];
 695        companion->dev = port->dev;
 696        companion->ops->attach(companion);
 697        return;
 698    }
 699
 700    *portsc |= PORTSC_CONNECT;
 701    *portsc |= PORTSC_CSC;
 702
 703    ehci_raise_irq(s, USBSTS_PCD);
 704}
 705
 706static void ehci_detach(USBPort *port)
 707{
 708    EHCIState *s = port->opaque;
 709    uint32_t *portsc = &s->portsc[port->index];
 710    const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
 711
 712    trace_usb_ehci_port_detach(port->index, owner);
 713
 714    if (*portsc & PORTSC_POWNER) {
 715        USBPort *companion = s->companion_ports[port->index];
 716        companion->ops->detach(companion);
 717        companion->dev = NULL;
 718        /*
 719         * EHCI spec 4.2.2: "When a disconnect occurs... On the event,
 720         * the port ownership is returned immediately to the EHCI controller."
 721         */
 722        *portsc &= ~PORTSC_POWNER;
 723        return;
 724    }
 725
 726    ehci_queues_rip_device(s, port->dev, 0);
 727    ehci_queues_rip_device(s, port->dev, 1);
 728
 729    *portsc &= ~(PORTSC_CONNECT|PORTSC_PED);
 730    *portsc |= PORTSC_CSC;
 731
 732    ehci_raise_irq(s, USBSTS_PCD);
 733}
 734
 735static void ehci_child_detach(USBPort *port, USBDevice *child)
 736{
 737    EHCIState *s = port->opaque;
 738    uint32_t portsc = s->portsc[port->index];
 739
 740    if (portsc & PORTSC_POWNER) {
 741        USBPort *companion = s->companion_ports[port->index];
 742        companion->ops->child_detach(companion, child);
 743        return;
 744    }
 745
 746    ehci_queues_rip_device(s, child, 0);
 747    ehci_queues_rip_device(s, child, 1);
 748}
 749
 750static void ehci_wakeup(USBPort *port)
 751{
 752    EHCIState *s = port->opaque;
 753    uint32_t *portsc = &s->portsc[port->index];
 754
 755    if (*portsc & PORTSC_POWNER) {
 756        USBPort *companion = s->companion_ports[port->index];
 757        if (companion->ops->wakeup) {
 758            companion->ops->wakeup(companion);
 759        }
 760        return;
 761    }
 762
 763    if (*portsc & PORTSC_SUSPEND) {
 764        trace_usb_ehci_port_wakeup(port->index);
 765        *portsc |= PORTSC_FPRES;
 766        ehci_raise_irq(s, USBSTS_PCD);
 767    }
 768
 769    qemu_bh_schedule(s->async_bh);
 770}
 771
 772static void ehci_register_companion(USBBus *bus, USBPort *ports[],
 773                                    uint32_t portcount, uint32_t firstport,
 774                                    Error **errp)
 775{
 776    EHCIState *s = container_of(bus, EHCIState, bus);
 777    uint32_t i;
 778
 779    if (firstport + portcount > NB_PORTS) {
 780        error_setg(errp, "firstport must be between 0 and %u",
 781                   NB_PORTS - portcount);
 782        return;
 783    }
 784
 785    for (i = 0; i < portcount; i++) {
 786        if (s->companion_ports[firstport + i]) {
 787            error_setg(errp, "firstport %u asks for ports %u-%u,"
 788                       " but port %u has a companion assigned already",
 789                       firstport, firstport, firstport + portcount - 1,
 790                       firstport + i);
 791            return;
 792        }
 793    }
 794
 795    for (i = 0; i < portcount; i++) {
 796        s->companion_ports[firstport + i] = ports[i];
 797        s->ports[firstport + i].speedmask |=
 798            USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL;
 799        /* Ensure devs attached before the initial reset go to the companion */
 800        s->portsc[firstport + i] = PORTSC_POWNER;
 801    }
 802
 803    s->companion_count++;
 804    s->caps[0x05] = (s->companion_count << 4) | portcount;
 805}
 806
 807static void ehci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
 808                                 unsigned int stream)
 809{
 810    EHCIState *s = container_of(bus, EHCIState, bus);
 811    uint32_t portsc = s->portsc[ep->dev->port->index];
 812
 813    if (portsc & PORTSC_POWNER) {
 814        return;
 815    }
 816
 817    s->periodic_sched_active = PERIODIC_ACTIVE;
 818    qemu_bh_schedule(s->async_bh);
 819}
 820
 821static USBDevice *ehci_find_device(EHCIState *ehci, uint8_t addr)
 822{
 823    USBDevice *dev;
 824    USBPort *port;
 825    int i;
 826
 827    for (i = 0; i < NB_PORTS; i++) {
 828        port = &ehci->ports[i];
 829        if (!(ehci->portsc[i] & PORTSC_PED)) {
 830            DPRINTF("Port %d not enabled\n", i);
 831            continue;
 832        }
 833        dev = usb_find_device(port, addr);
 834        if (dev != NULL) {
 835            return dev;
 836        }
 837    }
 838    return NULL;
 839}
 840
 841/* 4.1 host controller initialization */
 842void ehci_reset(void *opaque)
 843{
 844    EHCIState *s = opaque;
 845    int i;
 846    USBDevice *devs[NB_PORTS];
 847
 848    trace_usb_ehci_reset();
 849
 850    /*
 851     * Do the detach before touching portsc, so that it correctly gets send to
 852     * us or to our companion based on PORTSC_POWNER before the reset.
 853     */
 854    for(i = 0; i < NB_PORTS; i++) {
 855        devs[i] = s->ports[i].dev;
 856        if (devs[i] && devs[i]->attached) {
 857            usb_detach(&s->ports[i]);
 858        }
 859    }
 860
 861    memset(&s->opreg, 0x00, sizeof(s->opreg));
 862    memset(&s->portsc, 0x00, sizeof(s->portsc));
 863
 864    s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
 865    s->usbsts = USBSTS_HALT;
 866    s->usbsts_pending = 0;
 867    s->usbsts_frindex = 0;
 868
 869    s->astate = EST_INACTIVE;
 870    s->pstate = EST_INACTIVE;
 871
 872    for(i = 0; i < NB_PORTS; i++) {
 873        if (s->companion_ports[i]) {
 874            s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;
 875        } else {
 876            s->portsc[i] = PORTSC_PPOWER;
 877        }
 878        if (devs[i] && devs[i]->attached) {
 879            usb_attach(&s->ports[i]);
 880            usb_device_reset(devs[i]);
 881        }
 882    }
 883    ehci_queues_rip_all(s, 0);
 884    ehci_queues_rip_all(s, 1);
 885    timer_del(s->frame_timer);
 886    qemu_bh_cancel(s->async_bh);
 887}
 888
 889static uint64_t ehci_caps_read(void *ptr, hwaddr addr,
 890                               unsigned size)
 891{
 892    EHCIState *s = ptr;
 893    return s->caps[addr];
 894}
 895
 896static uint64_t ehci_opreg_read(void *ptr, hwaddr addr,
 897                                unsigned size)
 898{
 899    EHCIState *s = ptr;
 900    uint32_t val;
 901
 902    switch (addr) {
 903    case FRINDEX:
 904        /* Round down to mult of 8, else it can go backwards on migration */
 905        val = s->frindex & ~7;
 906        break;
 907    default:
 908        val = s->opreg[addr >> 2];
 909    }
 910
 911    trace_usb_ehci_opreg_read(addr + s->opregbase, addr2str(addr), val);
 912    return val;
 913}
 914
 915static uint64_t ehci_port_read(void *ptr, hwaddr addr,
 916                               unsigned size)
 917{
 918    EHCIState *s = ptr;
 919    uint32_t val;
 920
 921    val = s->portsc[addr >> 2];
 922    trace_usb_ehci_portsc_read(addr + s->portscbase, addr >> 2, val);
 923    return val;
 924}
 925
 926static void handle_port_owner_write(EHCIState *s, int port, uint32_t owner)
 927{
 928    USBDevice *dev = s->ports[port].dev;
 929    uint32_t *portsc = &s->portsc[port];
 930    uint32_t orig;
 931
 932    if (s->companion_ports[port] == NULL)
 933        return;
 934
 935    owner = owner & PORTSC_POWNER;
 936    orig  = *portsc & PORTSC_POWNER;
 937
 938    if (!(owner ^ orig)) {
 939        return;
 940    }
 941
 942    if (dev && dev->attached) {
 943        usb_detach(&s->ports[port]);
 944    }
 945
 946    *portsc &= ~PORTSC_POWNER;
 947    *portsc |= owner;
 948
 949    if (dev && dev->attached) {
 950        usb_attach(&s->ports[port]);
 951    }
 952}
 953
 954static void ehci_port_write(void *ptr, hwaddr addr,
 955                            uint64_t val, unsigned size)
 956{
 957    EHCIState *s = ptr;
 958    int port = addr >> 2;
 959    uint32_t *portsc = &s->portsc[port];
 960    uint32_t old = *portsc;
 961    USBDevice *dev = s->ports[port].dev;
 962
 963    trace_usb_ehci_portsc_write(addr + s->portscbase, addr >> 2, val);
 964
 965    /* Clear rwc bits */
 966    *portsc &= ~(val & PORTSC_RWC_MASK);
 967    /* The guest may clear, but not set the PED bit */
 968    *portsc &= val | ~PORTSC_PED;
 969    /* POWNER is masked out by RO_MASK as it is RO when we've no companion */
 970    handle_port_owner_write(s, port, val);
 971    /* And finally apply RO_MASK */
 972    val &= PORTSC_RO_MASK;
 973
 974    if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
 975        trace_usb_ehci_port_reset(port, 1);
 976    }
 977
 978    if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
 979        trace_usb_ehci_port_reset(port, 0);
 980        if (dev && dev->attached) {
 981            usb_port_reset(&s->ports[port]);
 982            *portsc &= ~PORTSC_CSC;
 983        }
 984
 985        /*
 986         *  Table 2.16 Set the enable bit(and enable bit change) to indicate
 987         *  to SW that this port has a high speed device attached
 988         */
 989        if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {
 990            val |= PORTSC_PED;
 991        }
 992    }
 993
 994    if ((val & PORTSC_SUSPEND) && !(*portsc & PORTSC_SUSPEND)) {
 995        trace_usb_ehci_port_suspend(port);
 996    }
 997    if (!(val & PORTSC_FPRES) && (*portsc & PORTSC_FPRES)) {
 998        trace_usb_ehci_port_resume(port);
 999        val &= ~PORTSC_SUSPEND;
1000    }
1001
1002    *portsc &= ~PORTSC_RO_MASK;
1003    *portsc |= val;
1004    trace_usb_ehci_portsc_change(addr + s->portscbase, addr >> 2, *portsc, old);
1005}
1006
1007static void ehci_opreg_write(void *ptr, hwaddr addr,
1008                             uint64_t val, unsigned size)
1009{
1010    EHCIState *s = ptr;
1011    uint32_t *mmio = s->opreg + (addr >> 2);
1012    uint32_t old = *mmio;
1013    int i;
1014
1015    trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);
1016
1017    switch (addr) {
1018    case USBCMD:
1019        if (val & USBCMD_HCRESET) {
1020            ehci_reset(s);
1021            val = s->usbcmd;
1022            break;
1023        }
1024
1025        /* not supporting dynamic frame list size at the moment */
1026        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
1027            fprintf(stderr, "attempt to set frame list size -- value %d\n",
1028                    (int)val & USBCMD_FLS);
1029            val &= ~USBCMD_FLS;
1030        }
1031
1032        if (val & USBCMD_IAAD) {
1033            /*
1034             * Process IAAD immediately, otherwise the Linux IAAD watchdog may
1035             * trigger and re-use a qh without us seeing the unlink.
1036             */
1037            s->async_stepdown = 0;
1038            qemu_bh_schedule(s->async_bh);
1039            trace_usb_ehci_doorbell_ring();
1040        }
1041
1042        if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
1043            ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
1044            if (s->pstate == EST_INACTIVE) {
1045                SET_LAST_RUN_CLOCK(s);
1046            }
1047            s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
1048            ehci_update_halt(s);
1049            s->async_stepdown = 0;
1050            qemu_bh_schedule(s->async_bh);
1051        }
1052        break;
1053
1054    case USBSTS:
1055        val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO
1056        ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC
1057        val = s->usbsts;
1058        ehci_update_irq(s);
1059        break;
1060
1061    case USBINTR:
1062        val &= USBINTR_MASK;
1063        if (ehci_enabled(s) && (USBSTS_FLR & val)) {
1064            qemu_bh_schedule(s->async_bh);
1065        }
1066        break;
1067
1068    case FRINDEX:
1069        val &= 0x00003fff; /* frindex is 14bits */
1070        s->usbsts_frindex = val;
1071        break;
1072
1073    case CONFIGFLAG:
1074        val &= 0x1;
1075        if (val) {
1076            for(i = 0; i < NB_PORTS; i++)
1077                handle_port_owner_write(s, i, 0);
1078        }
1079        break;
1080
1081    case PERIODICLISTBASE:
1082        if (ehci_periodic_enabled(s)) {
1083            fprintf(stderr,
1084              "ehci: PERIODIC list base register set while periodic schedule\n"
1085              "      is enabled and HC is enabled\n");
1086        }
1087        break;
1088
1089    case ASYNCLISTADDR:
1090        if (ehci_async_enabled(s)) {
1091            fprintf(stderr,
1092              "ehci: ASYNC list address register set while async schedule\n"
1093              "      is enabled and HC is enabled\n");
1094        }
1095        break;
1096    }
1097
1098    *mmio = val;
1099    trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),
1100                                *mmio, old);
1101}
1102
1103/*
1104 *  Write the qh back to guest physical memory.  This step isn't
1105 *  in the EHCI spec but we need to do it since we don't share
1106 *  physical memory with our guest VM.
1107 *
1108 *  The first three dwords are read-only for the EHCI, so skip them
1109 *  when writing back the qh.
1110 */
1111static void ehci_flush_qh(EHCIQueue *q)
1112{
1113    uint32_t *qh = (uint32_t *) &q->qh;
1114    uint32_t dwords = sizeof(EHCIqh) >> 2;
1115    uint32_t addr = NLPTR_GET(q->qhaddr);
1116
1117    put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
1118}
1119
1120// 4.10.2
1121
1122static int ehci_qh_do_overlay(EHCIQueue *q)
1123{
1124    EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1125    int i;
1126    int dtoggle;
1127    int ping;
1128    int eps;
1129    int reload;
1130
1131    assert(p != NULL);
1132    assert(p->qtdaddr == q->qtdaddr);
1133
1134    // remember values in fields to preserve in qh after overlay
1135
1136    dtoggle = q->qh.token & QTD_TOKEN_DTOGGLE;
1137    ping    = q->qh.token & QTD_TOKEN_PING;
1138
1139    q->qh.current_qtd = p->qtdaddr;
1140    q->qh.next_qtd    = p->qtd.next;
1141    q->qh.altnext_qtd = p->qtd.altnext;
1142    q->qh.token       = p->qtd.token;
1143
1144
1145    eps = get_field(q->qh.epchar, QH_EPCHAR_EPS);
1146    if (eps == EHCI_QH_EPS_HIGH) {
1147        q->qh.token &= ~QTD_TOKEN_PING;
1148        q->qh.token |= ping;
1149    }
1150
1151    reload = get_field(q->qh.epchar, QH_EPCHAR_RL);
1152    set_field(&q->qh.altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
1153
1154    for (i = 0; i < 5; i++) {
1155        q->qh.bufptr[i] = p->qtd.bufptr[i];
1156    }
1157
1158    if (!(q->qh.epchar & QH_EPCHAR_DTC)) {
1159        // preserve QH DT bit
1160        q->qh.token &= ~QTD_TOKEN_DTOGGLE;
1161        q->qh.token |= dtoggle;
1162    }
1163
1164    q->qh.bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
1165    q->qh.bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
1166
1167    ehci_flush_qh(q);
1168
1169    return 0;
1170}
1171
1172static int ehci_init_transfer(EHCIPacket *p)
1173{
1174    uint32_t cpage, offset, bytes, plen;
1175    dma_addr_t page;
1176
1177    cpage  = get_field(p->qtd.token, QTD_TOKEN_CPAGE);
1178    bytes  = get_field(p->qtd.token, QTD_TOKEN_TBYTES);
1179    offset = p->qtd.bufptr[0] & ~QTD_BUFPTR_MASK;
1180    qemu_sglist_init(&p->sgl, p->queue->ehci->device, 5, p->queue->ehci->as);
1181
1182    while (bytes > 0) {
1183        if (cpage > 4) {
1184            fprintf(stderr, "cpage out of range (%d)\n", cpage);
1185            return -1;
1186        }
1187
1188        page  = p->qtd.bufptr[cpage] & QTD_BUFPTR_MASK;
1189        page += offset;
1190        plen  = bytes;
1191        if (plen > 4096 - offset) {
1192            plen = 4096 - offset;
1193            offset = 0;
1194            cpage++;
1195        }
1196
1197        qemu_sglist_add(&p->sgl, page, plen);
1198        bytes -= plen;
1199    }
1200    return 0;
1201}
1202
1203static void ehci_finish_transfer(EHCIQueue *q, int len)
1204{
1205    uint32_t cpage, offset;
1206
1207    if (len > 0) {
1208        /* update cpage & offset */
1209        cpage  = get_field(q->qh.token, QTD_TOKEN_CPAGE);
1210        offset = q->qh.bufptr[0] & ~QTD_BUFPTR_MASK;
1211
1212        offset += len;
1213        cpage  += offset >> QTD_BUFPTR_SH;
1214        offset &= ~QTD_BUFPTR_MASK;
1215
1216        set_field(&q->qh.token, cpage, QTD_TOKEN_CPAGE);
1217        q->qh.bufptr[0] &= QTD_BUFPTR_MASK;
1218        q->qh.bufptr[0] |= offset;
1219    }
1220}
1221
1222static void ehci_async_complete_packet(USBPort *port, USBPacket *packet)
1223{
1224    EHCIPacket *p;
1225    EHCIState *s = port->opaque;
1226    uint32_t portsc = s->portsc[port->index];
1227
1228    if (portsc & PORTSC_POWNER) {
1229        USBPort *companion = s->companion_ports[port->index];
1230        companion->ops->complete(companion, packet);
1231        return;
1232    }
1233
1234    p = container_of(packet, EHCIPacket, packet);
1235    assert(p->async == EHCI_ASYNC_INFLIGHT);
1236
1237    if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
1238        trace_usb_ehci_packet_action(p->queue, p, "remove");
1239        ehci_free_packet(p);
1240        return;
1241    }
1242
1243    trace_usb_ehci_packet_action(p->queue, p, "wakeup");
1244    p->async = EHCI_ASYNC_FINISHED;
1245
1246    if (!p->queue->async) {
1247        s->periodic_sched_active = PERIODIC_ACTIVE;
1248    }
1249    qemu_bh_schedule(s->async_bh);
1250}
1251
1252static void ehci_execute_complete(EHCIQueue *q)
1253{
1254    EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1255    uint32_t tbytes;
1256
1257    assert(p != NULL);
1258    assert(p->qtdaddr == q->qtdaddr);
1259    assert(p->async == EHCI_ASYNC_INITIALIZED ||
1260           p->async == EHCI_ASYNC_FINISHED);
1261
1262    DPRINTF("execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, "
1263            "status %d, actual_length %d\n",
1264            q->qhaddr, q->qh.next, q->qtdaddr,
1265            p->packet.status, p->packet.actual_length);
1266
1267    switch (p->packet.status) {
1268    case USB_RET_SUCCESS:
1269        break;
1270    case USB_RET_IOERROR:
1271    case USB_RET_NODEV:
1272        q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);
1273        set_field(&q->qh.token, 0, QTD_TOKEN_CERR);
1274        ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1275        break;
1276    case USB_RET_STALL:
1277        q->qh.token |= QTD_TOKEN_HALT;
1278        ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1279        break;
1280    case USB_RET_NAK:
1281        set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);
1282        return; /* We're not done yet with this transaction */
1283    case USB_RET_BABBLE:
1284        q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
1285        ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1286        break;
1287    default:
1288        /* should not be triggerable */
1289        fprintf(stderr, "USB invalid response %d\n", p->packet.status);
1290        g_assert_not_reached();
1291        break;
1292    }
1293
1294    /* TODO check 4.12 for splits */
1295    tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES);
1296    if (tbytes && p->pid == USB_TOKEN_IN) {
1297        tbytes -= p->packet.actual_length;
1298        if (tbytes) {
1299            /* 4.15.1.2 must raise int on a short input packet */
1300            ehci_raise_irq(q->ehci, USBSTS_INT);
1301            if (q->async) {
1302                q->ehci->int_req_by_async = true;
1303            }
1304        }
1305    } else {
1306        tbytes = 0;
1307    }
1308    DPRINTF("updating tbytes to %d\n", tbytes);
1309    set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES);
1310
1311    ehci_finish_transfer(q, p->packet.actual_length);
1312    usb_packet_unmap(&p->packet, &p->sgl);
1313    qemu_sglist_destroy(&p->sgl);
1314    p->async = EHCI_ASYNC_NONE;
1315
1316    q->qh.token ^= QTD_TOKEN_DTOGGLE;
1317    q->qh.token &= ~QTD_TOKEN_ACTIVE;
1318
1319    if (q->qh.token & QTD_TOKEN_IOC) {
1320        ehci_raise_irq(q->ehci, USBSTS_INT);
1321        if (q->async) {
1322            q->ehci->int_req_by_async = true;
1323        }
1324    }
1325}
1326
1327/* 4.10.3 returns "again" */
1328static int ehci_execute(EHCIPacket *p, const char *action)
1329{
1330    USBEndpoint *ep;
1331    int endp;
1332    bool spd;
1333
1334    assert(p->async == EHCI_ASYNC_NONE ||
1335           p->async == EHCI_ASYNC_INITIALIZED);
1336
1337    if (!(p->qtd.token & QTD_TOKEN_ACTIVE)) {
1338        fprintf(stderr, "Attempting to execute inactive qtd\n");
1339        return -1;
1340    }
1341
1342    if (get_field(p->qtd.token, QTD_TOKEN_TBYTES) > BUFF_SIZE) {
1343        ehci_trace_guest_bug(p->queue->ehci,
1344                             "guest requested more bytes than allowed");
1345        return -1;
1346    }
1347
1348    if (!ehci_verify_pid(p->queue, &p->qtd)) {
1349        ehci_queue_stopped(p->queue); /* Mark the ep in the prev dir stopped */
1350    }
1351    p->pid = ehci_get_pid(&p->qtd);
1352    p->queue->last_pid = p->pid;
1353    endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
1354    ep = usb_ep_get(p->queue->dev, p->pid, endp);
1355
1356    if (p->async == EHCI_ASYNC_NONE) {
1357        if (ehci_init_transfer(p) != 0) {
1358            return -1;
1359        }
1360
1361        spd = (p->pid == USB_TOKEN_IN && NLPTR_TBIT(p->qtd.altnext) == 0);
1362        usb_packet_setup(&p->packet, p->pid, ep, 0, p->qtdaddr, spd,
1363                         (p->qtd.token & QTD_TOKEN_IOC) != 0);
1364        usb_packet_map(&p->packet, &p->sgl);
1365        p->async = EHCI_ASYNC_INITIALIZED;
1366    }
1367
1368    trace_usb_ehci_packet_action(p->queue, p, action);
1369    usb_handle_packet(p->queue->dev, &p->packet);
1370    DPRINTF("submit: qh 0x%x next 0x%x qtd 0x%x pid 0x%x len %zd endp 0x%x "
1371            "status %d actual_length %d\n", p->queue->qhaddr, p->qtd.next,
1372            p->qtdaddr, p->pid, p->packet.iov.size, endp, p->packet.status,
1373            p->packet.actual_length);
1374
1375    if (p->packet.actual_length > BUFF_SIZE) {
1376        fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");
1377        return -1;
1378    }
1379
1380    return 1;
1381}
1382
1383/*  4.7.2
1384 */
1385
1386static int ehci_process_itd(EHCIState *ehci,
1387                            EHCIitd *itd,
1388                            uint32_t addr)
1389{
1390    USBDevice *dev;
1391    USBEndpoint *ep;
1392    uint32_t i, len, pid, dir, devaddr, endp;
1393    uint32_t pg, off, ptr1, ptr2, max, mult;
1394
1395    ehci->periodic_sched_active = PERIODIC_ACTIVE;
1396
1397    dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
1398    devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
1399    endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
1400    max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
1401    mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
1402
1403    for(i = 0; i < 8; i++) {
1404        if (itd->transact[i] & ITD_XACT_ACTIVE) {
1405            pg   = get_field(itd->transact[i], ITD_XACT_PGSEL);
1406            off  = itd->transact[i] & ITD_XACT_OFFSET_MASK;
1407            ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
1408            ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
1409            len  = get_field(itd->transact[i], ITD_XACT_LENGTH);
1410
1411            if (len > max * mult) {
1412                len = max * mult;
1413            }
1414
1415            if (len > BUFF_SIZE) {
1416                return -1;
1417            }
1418
1419            qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
1420            if (off + len > 4096) {
1421                /* transfer crosses page border */
1422                uint32_t len2 = off + len - 4096;
1423                uint32_t len1 = len - len2;
1424                qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
1425                qemu_sglist_add(&ehci->isgl, ptr2, len2);
1426            } else {
1427                qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
1428            }
1429
1430            pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
1431
1432            dev = ehci_find_device(ehci, devaddr);
1433            ep = usb_ep_get(dev, pid, endp);
1434            if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
1435                usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
1436                                 (itd->transact[i] & ITD_XACT_IOC) != 0);
1437                usb_packet_map(&ehci->ipacket, &ehci->isgl);
1438                usb_handle_packet(dev, &ehci->ipacket);
1439                usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
1440            } else {
1441                DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
1442                ehci->ipacket.status = USB_RET_NAK;
1443                ehci->ipacket.actual_length = 0;
1444            }
1445            qemu_sglist_destroy(&ehci->isgl);
1446
1447            switch (ehci->ipacket.status) {
1448            case USB_RET_SUCCESS:
1449                break;
1450            default:
1451                fprintf(stderr, "Unexpected iso usb result: %d\n",
1452                        ehci->ipacket.status);
1453                /* Fall through */
1454            case USB_RET_IOERROR:
1455            case USB_RET_NODEV:
1456                /* 3.3.2: XACTERR is only allowed on IN transactions */
1457                if (dir) {
1458                    itd->transact[i] |= ITD_XACT_XACTERR;
1459                    ehci_raise_irq(ehci, USBSTS_ERRINT);
1460                }
1461                break;
1462            case USB_RET_BABBLE:
1463                itd->transact[i] |= ITD_XACT_BABBLE;
1464                ehci_raise_irq(ehci, USBSTS_ERRINT);
1465                break;
1466            case USB_RET_NAK:
1467                /* no data for us, so do a zero-length transfer */
1468                ehci->ipacket.actual_length = 0;
1469                break;
1470            }
1471            if (!dir) {
1472                set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
1473                          ITD_XACT_LENGTH); /* OUT */
1474            } else {
1475                set_field(&itd->transact[i], ehci->ipacket.actual_length,
1476                          ITD_XACT_LENGTH); /* IN */
1477            }
1478            if (itd->transact[i] & ITD_XACT_IOC) {
1479                ehci_raise_irq(ehci, USBSTS_INT);
1480            }
1481            itd->transact[i] &= ~ITD_XACT_ACTIVE;
1482        }
1483    }
1484    return 0;
1485}
1486
1487
1488/*  This state is the entry point for asynchronous schedule
1489 *  processing.  Entry here consitutes a EHCI start event state (4.8.5)
1490 */
1491static int ehci_state_waitlisthead(EHCIState *ehci,  int async)
1492{
1493    EHCIqh qh;
1494    int i = 0;
1495    int again = 0;
1496    uint32_t entry = ehci->asynclistaddr;
1497
1498    /* set reclamation flag at start event (4.8.6) */
1499    if (async) {
1500        ehci_set_usbsts(ehci, USBSTS_REC);
1501    }
1502
1503    ehci_queues_rip_unused(ehci, async);
1504
1505    /*  Find the head of the list (4.9.1.1) */
1506    for(i = 0; i < MAX_QH; i++) {
1507        if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &qh,
1508                       sizeof(EHCIqh) >> 2) < 0) {
1509            return 0;
1510        }
1511        ehci_trace_qh(NULL, NLPTR_GET(entry), &qh);
1512
1513        if (qh.epchar & QH_EPCHAR_H) {
1514            if (async) {
1515                entry |= (NLPTR_TYPE_QH << 1);
1516            }
1517
1518            ehci_set_fetch_addr(ehci, async, entry);
1519            ehci_set_state(ehci, async, EST_FETCHENTRY);
1520            again = 1;
1521            goto out;
1522        }
1523
1524        entry = qh.next;
1525        if (entry == ehci->asynclistaddr) {
1526            break;
1527        }
1528    }
1529
1530    /* no head found for list. */
1531
1532    ehci_set_state(ehci, async, EST_ACTIVE);
1533
1534out:
1535    return again;
1536}
1537
1538
1539/*  This state is the entry point for periodic schedule processing as
1540 *  well as being a continuation state for async processing.
1541 */
1542static int ehci_state_fetchentry(EHCIState *ehci, int async)
1543{
1544    int again = 0;
1545    uint32_t entry = ehci_get_fetch_addr(ehci, async);
1546
1547    if (NLPTR_TBIT(entry)) {
1548        ehci_set_state(ehci, async, EST_ACTIVE);
1549        goto out;
1550    }
1551
1552    /* section 4.8, only QH in async schedule */
1553    if (async && (NLPTR_TYPE_GET(entry) != NLPTR_TYPE_QH)) {
1554        fprintf(stderr, "non queue head request in async schedule\n");
1555        return -1;
1556    }
1557
1558    switch (NLPTR_TYPE_GET(entry)) {
1559    case NLPTR_TYPE_QH:
1560        ehci_set_state(ehci, async, EST_FETCHQH);
1561        again = 1;
1562        break;
1563
1564    case NLPTR_TYPE_ITD:
1565        ehci_set_state(ehci, async, EST_FETCHITD);
1566        again = 1;
1567        break;
1568
1569    case NLPTR_TYPE_STITD:
1570        ehci_set_state(ehci, async, EST_FETCHSITD);
1571        again = 1;
1572        break;
1573
1574    default:
1575        /* TODO: handle FSTN type */
1576        fprintf(stderr, "FETCHENTRY: entry at %X is of type %d "
1577                "which is not supported yet\n", entry, NLPTR_TYPE_GET(entry));
1578        return -1;
1579    }
1580
1581out:
1582    return again;
1583}
1584
1585static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
1586{
1587    uint32_t entry;
1588    EHCIQueue *q;
1589    EHCIqh qh;
1590
1591    entry = ehci_get_fetch_addr(ehci, async);
1592    q = ehci_find_queue_by_qh(ehci, entry, async);
1593    if (q == NULL) {
1594        q = ehci_alloc_queue(ehci, entry, async);
1595    }
1596
1597    q->seen++;
1598    if (q->seen > 1) {
1599        /* we are going in circles -- stop processing */
1600        ehci_set_state(ehci, async, EST_ACTIVE);
1601        q = NULL;
1602        goto out;
1603    }
1604
1605    if (get_dwords(ehci, NLPTR_GET(q->qhaddr),
1606                   (uint32_t *) &qh, sizeof(EHCIqh) >> 2) < 0) {
1607        q = NULL;
1608        goto out;
1609    }
1610    ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &qh);
1611
1612    /*
1613     * The overlay area of the qh should never be changed by the guest,
1614     * except when idle, in which case the reset is a nop.
1615     */
1616    if (!ehci_verify_qh(q, &qh)) {
1617        if (ehci_reset_queue(q) > 0) {
1618            ehci_trace_guest_bug(ehci, "guest updated active QH");
1619        }
1620    }
1621    q->qh = qh;
1622
1623    q->transact_ctr = get_field(q->qh.epcap, QH_EPCAP_MULT);
1624    if (q->transact_ctr == 0) { /* Guest bug in some versions of windows */
1625        q->transact_ctr = 4;
1626    }
1627
1628    if (q->dev == NULL) {
1629        q->dev = ehci_find_device(q->ehci,
1630                                  get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
1631    }
1632
1633    if (async && (q->qh.epchar & QH_EPCHAR_H)) {
1634
1635        /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
1636        if (ehci->usbsts & USBSTS_REC) {
1637            ehci_clear_usbsts(ehci, USBSTS_REC);
1638        } else {
1639            DPRINTF("FETCHQH:  QH 0x%08x. H-bit set, reclamation status reset"
1640                       " - done processing\n", q->qhaddr);
1641            ehci_set_state(ehci, async, EST_ACTIVE);
1642            q = NULL;
1643            goto out;
1644        }
1645    }
1646
1647#if EHCI_DEBUG
1648    if (q->qhaddr != q->qh.next) {
1649    DPRINTF("FETCHQH:  QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",
1650               q->qhaddr,
1651               q->qh.epchar & QH_EPCHAR_H,
1652               q->qh.token & QTD_TOKEN_HALT,
1653               q->qh.token & QTD_TOKEN_ACTIVE,
1654               q->qh.next);
1655    }
1656#endif
1657
1658    if (q->qh.token & QTD_TOKEN_HALT) {
1659        ehci_set_state(ehci, async, EST_HORIZONTALQH);
1660
1661    } else if ((q->qh.token & QTD_TOKEN_ACTIVE) &&
1662               (NLPTR_TBIT(q->qh.current_qtd) == 0)) {
1663        q->qtdaddr = q->qh.current_qtd;
1664        ehci_set_state(ehci, async, EST_FETCHQTD);
1665
1666    } else {
1667        /*  EHCI spec version 1.0 Section 4.10.2 */
1668        ehci_set_state(ehci, async, EST_ADVANCEQUEUE);
1669    }
1670
1671out:
1672    return q;
1673}
1674
1675static int ehci_state_fetchitd(EHCIState *ehci, int async)
1676{
1677    uint32_t entry;
1678    EHCIitd itd;
1679
1680    assert(!async);
1681    entry = ehci_get_fetch_addr(ehci, async);
1682
1683    if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1684                   sizeof(EHCIitd) >> 2) < 0) {
1685        return -1;
1686    }
1687    ehci_trace_itd(ehci, entry, &itd);
1688
1689    if (ehci_process_itd(ehci, &itd, entry) != 0) {
1690        return -1;
1691    }
1692
1693    put_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1694               sizeof(EHCIitd) >> 2);
1695    ehci_set_fetch_addr(ehci, async, itd.next);
1696    ehci_set_state(ehci, async, EST_FETCHENTRY);
1697
1698    return 1;
1699}
1700
1701static int ehci_state_fetchsitd(EHCIState *ehci, int async)
1702{
1703    uint32_t entry;
1704    EHCIsitd sitd;
1705
1706    assert(!async);
1707    entry = ehci_get_fetch_addr(ehci, async);
1708
1709    if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *)&sitd,
1710                   sizeof(EHCIsitd) >> 2) < 0) {
1711        return 0;
1712    }
1713    ehci_trace_sitd(ehci, entry, &sitd);
1714
1715    if (!(sitd.results & SITD_RESULTS_ACTIVE)) {
1716        /* siTD is not active, nothing to do */;
1717    } else {
1718        /* TODO: split transfers are not implemented */
1719        fprintf(stderr, "WARNING: Skipping active siTD\n");
1720    }
1721
1722    ehci_set_fetch_addr(ehci, async, sitd.next);
1723    ehci_set_state(ehci, async, EST_FETCHENTRY);
1724    return 1;
1725}
1726
1727/* Section 4.10.2 - paragraph 3 */
1728static int ehci_state_advqueue(EHCIQueue *q)
1729{
1730#if 0
1731    /* TO-DO: 4.10.2 - paragraph 2
1732     * if I-bit is set to 1 and QH is not active
1733     * go to horizontal QH
1734     */
1735    if (I-bit set) {
1736        ehci_set_state(ehci, async, EST_HORIZONTALQH);
1737        goto out;
1738    }
1739#endif
1740
1741    /*
1742     * want data and alt-next qTD is valid
1743     */
1744    if (((q->qh.token & QTD_TOKEN_TBYTES_MASK) != 0) &&
1745        (NLPTR_TBIT(q->qh.altnext_qtd) == 0)) {
1746        q->qtdaddr = q->qh.altnext_qtd;
1747        ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1748
1749    /*
1750     *  next qTD is valid
1751     */
1752    } else if (NLPTR_TBIT(q->qh.next_qtd) == 0) {
1753        q->qtdaddr = q->qh.next_qtd;
1754        ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1755
1756    /*
1757     *  no valid qTD, try next QH
1758     */
1759    } else {
1760        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1761    }
1762
1763    return 1;
1764}
1765
1766/* Section 4.10.2 - paragraph 4 */
1767static int ehci_state_fetchqtd(EHCIQueue *q)
1768{
1769    EHCIqtd qtd;
1770    EHCIPacket *p;
1771    int again = 1;
1772
1773    if (get_dwords(q->ehci, NLPTR_GET(q->qtdaddr), (uint32_t *) &qtd,
1774                   sizeof(EHCIqtd) >> 2) < 0) {
1775        return 0;
1776    }
1777    ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &qtd);
1778
1779    p = QTAILQ_FIRST(&q->packets);
1780    if (p != NULL) {
1781        if (!ehci_verify_qtd(p, &qtd)) {
1782            ehci_cancel_queue(q);
1783            if (qtd.token & QTD_TOKEN_ACTIVE) {
1784                ehci_trace_guest_bug(q->ehci, "guest updated active qTD");
1785            }
1786            p = NULL;
1787        } else {
1788            p->qtd = qtd;
1789            ehci_qh_do_overlay(q);
1790        }
1791    }
1792
1793    if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1794        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1795    } else if (p != NULL) {
1796        switch (p->async) {
1797        case EHCI_ASYNC_NONE:
1798        case EHCI_ASYNC_INITIALIZED:
1799            /* Not yet executed (MULT), or previously nacked (int) packet */
1800            ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1801            break;
1802        case EHCI_ASYNC_INFLIGHT:
1803            /* Check if the guest has added new tds to the queue */
1804            again = ehci_fill_queue(QTAILQ_LAST(&q->packets, pkts_head));
1805            /* Unfinished async handled packet, go horizontal */
1806            ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1807            break;
1808        case EHCI_ASYNC_FINISHED:
1809            /* Complete executing of the packet */
1810            ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1811            break;
1812        }
1813    } else {
1814        p = ehci_alloc_packet(q);
1815        p->qtdaddr = q->qtdaddr;
1816        p->qtd = qtd;
1817        ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1818    }
1819
1820    return again;
1821}
1822
1823static int ehci_state_horizqh(EHCIQueue *q)
1824{
1825    int again = 0;
1826
1827    if (ehci_get_fetch_addr(q->ehci, q->async) != q->qh.next) {
1828        ehci_set_fetch_addr(q->ehci, q->async, q->qh.next);
1829        ehci_set_state(q->ehci, q->async, EST_FETCHENTRY);
1830        again = 1;
1831    } else {
1832        ehci_set_state(q->ehci, q->async, EST_ACTIVE);
1833    }
1834
1835    return again;
1836}
1837
1838/* Returns "again" */
1839static int ehci_fill_queue(EHCIPacket *p)
1840{
1841    USBEndpoint *ep = p->packet.ep;
1842    EHCIQueue *q = p->queue;
1843    EHCIqtd qtd = p->qtd;
1844    uint32_t qtdaddr;
1845
1846    for (;;) {
1847        if (NLPTR_TBIT(qtd.next) != 0) {
1848            break;
1849        }
1850        qtdaddr = qtd.next;
1851        /*
1852         * Detect circular td lists, Windows creates these, counting on the
1853         * active bit going low after execution to make the queue stop.
1854         */
1855        QTAILQ_FOREACH(p, &q->packets, next) {
1856            if (p->qtdaddr == qtdaddr) {
1857                goto leave;
1858            }
1859        }
1860        if (get_dwords(q->ehci, NLPTR_GET(qtdaddr),
1861                       (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2) < 0) {
1862            return -1;
1863        }
1864        ehci_trace_qtd(q, NLPTR_GET(qtdaddr), &qtd);
1865        if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1866            break;
1867        }
1868        if (!ehci_verify_pid(q, &qtd)) {
1869            ehci_trace_guest_bug(q->ehci, "guest queued token with wrong pid");
1870            break;
1871        }
1872        p = ehci_alloc_packet(q);
1873        p->qtdaddr = qtdaddr;
1874        p->qtd = qtd;
1875        if (ehci_execute(p, "queue") == -1) {
1876            return -1;
1877        }
1878        assert(p->packet.status == USB_RET_ASYNC);
1879        p->async = EHCI_ASYNC_INFLIGHT;
1880    }
1881leave:
1882    usb_device_flush_ep_queue(ep->dev, ep);
1883    return 1;
1884}
1885
1886static int ehci_state_execute(EHCIQueue *q)
1887{
1888    EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1889    int again = 0;
1890
1891    assert(p != NULL);
1892    assert(p->qtdaddr == q->qtdaddr);
1893
1894    if (ehci_qh_do_overlay(q) != 0) {
1895        return -1;
1896    }
1897
1898    // TODO verify enough time remains in the uframe as in 4.4.1.1
1899    // TODO write back ptr to async list when done or out of time
1900
1901    /* 4.10.3, bottom of page 82, go horizontal on transaction counter == 0 */
1902    if (!q->async && q->transact_ctr == 0) {
1903        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1904        again = 1;
1905        goto out;
1906    }
1907
1908    if (q->async) {
1909        ehci_set_usbsts(q->ehci, USBSTS_REC);
1910    }
1911
1912    again = ehci_execute(p, "process");
1913    if (again == -1) {
1914        goto out;
1915    }
1916    if (p->packet.status == USB_RET_ASYNC) {
1917        ehci_flush_qh(q);
1918        trace_usb_ehci_packet_action(p->queue, p, "async");
1919        p->async = EHCI_ASYNC_INFLIGHT;
1920        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1921        if (q->async) {
1922            again = ehci_fill_queue(p);
1923        } else {
1924            again = 1;
1925        }
1926        goto out;
1927    }
1928
1929    ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1930    again = 1;
1931
1932out:
1933    return again;
1934}
1935
1936static int ehci_state_executing(EHCIQueue *q)
1937{
1938    EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1939
1940    assert(p != NULL);
1941    assert(p->qtdaddr == q->qtdaddr);
1942
1943    ehci_execute_complete(q);
1944
1945    /* 4.10.3 */
1946    if (!q->async && q->transact_ctr > 0) {
1947        q->transact_ctr--;
1948    }
1949
1950    /* 4.10.5 */
1951    if (p->packet.status == USB_RET_NAK) {
1952        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1953    } else {
1954        ehci_set_state(q->ehci, q->async, EST_WRITEBACK);
1955    }
1956
1957    ehci_flush_qh(q);
1958    return 1;
1959}
1960
1961
1962static int ehci_state_writeback(EHCIQueue *q)
1963{
1964    EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1965    uint32_t *qtd, addr;
1966    int again = 0;
1967
1968    /*  Write back the QTD from the QH area */
1969    assert(p != NULL);
1970    assert(p->qtdaddr == q->qtdaddr);
1971
1972    ehci_trace_qtd(q, NLPTR_GET(p->qtdaddr), (EHCIqtd *) &q->qh.next_qtd);
1973    qtd = (uint32_t *) &q->qh.next_qtd;
1974    addr = NLPTR_GET(p->qtdaddr);
1975    put_dwords(q->ehci, addr + 2 * sizeof(uint32_t), qtd + 2, 2);
1976    ehci_free_packet(p);
1977
1978    /*
1979     * EHCI specs say go horizontal here.
1980     *
1981     * We can also advance the queue here for performance reasons.  We
1982     * need to take care to only take that shortcut in case we've
1983     * processed the qtd just written back without errors, i.e. halt
1984     * bit is clear.
1985     */
1986    if (q->qh.token & QTD_TOKEN_HALT) {
1987        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1988        again = 1;
1989    } else {
1990        ehci_set_state(q->ehci, q->async, EST_ADVANCEQUEUE);
1991        again = 1;
1992    }
1993    return again;
1994}
1995
1996/*
1997 * This is the state machine that is common to both async and periodic
1998 */
1999
2000static void ehci_advance_state(EHCIState *ehci, int async)
2001{
2002    EHCIQueue *q = NULL;
2003    int again;
2004
2005    do {
2006        switch(ehci_get_state(ehci, async)) {
2007        case EST_WAITLISTHEAD:
2008            again = ehci_state_waitlisthead(ehci, async);
2009            break;
2010
2011        case EST_FETCHENTRY:
2012            again = ehci_state_fetchentry(ehci, async);
2013            break;
2014
2015        case EST_FETCHQH:
2016            q = ehci_state_fetchqh(ehci, async);
2017            if (q != NULL) {
2018                assert(q->async == async);
2019                again = 1;
2020            } else {
2021                again = 0;
2022            }
2023            break;
2024
2025        case EST_FETCHITD:
2026            again = ehci_state_fetchitd(ehci, async);
2027            break;
2028
2029        case EST_FETCHSITD:
2030            again = ehci_state_fetchsitd(ehci, async);
2031            break;
2032
2033        case EST_ADVANCEQUEUE:
2034            assert(q != NULL);
2035            again = ehci_state_advqueue(q);
2036            break;
2037
2038        case EST_FETCHQTD:
2039            assert(q != NULL);
2040            again = ehci_state_fetchqtd(q);
2041            break;
2042
2043        case EST_HORIZONTALQH:
2044            assert(q != NULL);
2045            again = ehci_state_horizqh(q);
2046            break;
2047
2048        case EST_EXECUTE:
2049            assert(q != NULL);
2050            again = ehci_state_execute(q);
2051            if (async) {
2052                ehci->async_stepdown = 0;
2053            }
2054            break;
2055
2056        case EST_EXECUTING:
2057            assert(q != NULL);
2058            if (async) {
2059                ehci->async_stepdown = 0;
2060            }
2061            again = ehci_state_executing(q);
2062            break;
2063
2064        case EST_WRITEBACK:
2065            assert(q != NULL);
2066            again = ehci_state_writeback(q);
2067            if (!async) {
2068                ehci->periodic_sched_active = PERIODIC_ACTIVE;
2069            }
2070            break;
2071
2072        default:
2073            fprintf(stderr, "Bad state!\n");
2074            again = -1;
2075            g_assert_not_reached();
2076            break;
2077        }
2078
2079        if (again < 0) {
2080            fprintf(stderr, "processing error - resetting ehci HC\n");
2081            ehci_reset(ehci);
2082            again = 0;
2083        }
2084    }
2085    while (again);
2086}
2087
2088static void ehci_advance_async_state(EHCIState *ehci)
2089{
2090    const int async = 1;
2091
2092    switch(ehci_get_state(ehci, async)) {
2093    case EST_INACTIVE:
2094        if (!ehci_async_enabled(ehci)) {
2095            break;
2096        }
2097        ehci_set_state(ehci, async, EST_ACTIVE);
2098        // No break, fall through to ACTIVE
2099
2100    case EST_ACTIVE:
2101        if (!ehci_async_enabled(ehci)) {
2102            ehci_queues_rip_all(ehci, async);
2103            ehci_set_state(ehci, async, EST_INACTIVE);
2104            break;
2105        }
2106
2107        /* make sure guest has acknowledged the doorbell interrupt */
2108        /* TO-DO: is this really needed? */
2109        if (ehci->usbsts & USBSTS_IAA) {
2110            DPRINTF("IAA status bit still set.\n");
2111            break;
2112        }
2113
2114        /* check that address register has been set */
2115        if (ehci->asynclistaddr == 0) {
2116            break;
2117        }
2118
2119        ehci_set_state(ehci, async, EST_WAITLISTHEAD);
2120        ehci_advance_state(ehci, async);
2121
2122        /* If the doorbell is set, the guest wants to make a change to the
2123         * schedule. The host controller needs to release cached data.
2124         * (section 4.8.2)
2125         */
2126        if (ehci->usbcmd & USBCMD_IAAD) {
2127            /* Remove all unseen qhs from the async qhs queue */
2128            ehci_queues_rip_unseen(ehci, async);
2129            trace_usb_ehci_doorbell_ack();
2130            ehci->usbcmd &= ~USBCMD_IAAD;
2131            ehci_raise_irq(ehci, USBSTS_IAA);
2132        }
2133        break;
2134
2135    default:
2136        /* this should only be due to a developer mistake */
2137        fprintf(stderr, "ehci: Bad asynchronous state %d. "
2138                "Resetting to active\n", ehci->astate);
2139        g_assert_not_reached();
2140    }
2141}
2142
2143static void ehci_advance_periodic_state(EHCIState *ehci)
2144{
2145    uint32_t entry;
2146    uint32_t list;
2147    const int async = 0;
2148
2149    // 4.6
2150
2151    switch(ehci_get_state(ehci, async)) {
2152    case EST_INACTIVE:
2153        if (!(ehci->frindex & 7) && ehci_periodic_enabled(ehci)) {
2154            ehci_set_state(ehci, async, EST_ACTIVE);
2155            // No break, fall through to ACTIVE
2156        } else
2157            break;
2158
2159    case EST_ACTIVE:
2160        if (!(ehci->frindex & 7) && !ehci_periodic_enabled(ehci)) {
2161            ehci_queues_rip_all(ehci, async);
2162            ehci_set_state(ehci, async, EST_INACTIVE);
2163            break;
2164        }
2165
2166        list = ehci->periodiclistbase & 0xfffff000;
2167        /* check that register has been set */
2168        if (list == 0) {
2169            break;
2170        }
2171        list |= ((ehci->frindex & 0x1ff8) >> 1);
2172
2173        if (get_dwords(ehci, list, &entry, 1) < 0) {
2174            break;
2175        }
2176
2177        DPRINTF("PERIODIC state adv fr=%d.  [%08X] -> %08X\n",
2178                ehci->frindex / 8, list, entry);
2179        ehci_set_fetch_addr(ehci, async,entry);
2180        ehci_set_state(ehci, async, EST_FETCHENTRY);
2181        ehci_advance_state(ehci, async);
2182        ehci_queues_rip_unused(ehci, async);
2183        break;
2184
2185    default:
2186        /* this should only be due to a developer mistake */
2187        fprintf(stderr, "ehci: Bad periodic state %d. "
2188                "Resetting to active\n", ehci->pstate);
2189        g_assert_not_reached();
2190    }
2191}
2192
2193static void ehci_update_frindex(EHCIState *ehci, int uframes)
2194{
2195    int i;
2196
2197    if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {
2198        return;
2199    }
2200
2201    for (i = 0; i < uframes; i++) {
2202        ehci->frindex++;
2203
2204        if (ehci->frindex == 0x00002000) {
2205            ehci_raise_irq(ehci, USBSTS_FLR);
2206        }
2207
2208        if (ehci->frindex == 0x00004000) {
2209            ehci_raise_irq(ehci, USBSTS_FLR);
2210            ehci->frindex = 0;
2211            if (ehci->usbsts_frindex >= 0x00004000) {
2212                ehci->usbsts_frindex -= 0x00004000;
2213            } else {
2214                ehci->usbsts_frindex = 0;
2215            }
2216        }
2217    }
2218}
2219
2220static void ehci_frame_timer(void *opaque)
2221{
2222    EHCIState *ehci = opaque;
2223    int need_timer = 0;
2224    int64_t expire_time, t_now;
2225    uint64_t ns_elapsed;
2226    int uframes, skipped_uframes;
2227    int i;
2228
2229    t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2230    ns_elapsed = t_now - ehci->last_run_ns;
2231    uframes = ns_elapsed / UFRAME_TIMER_NS;
2232
2233    if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
2234        need_timer++;
2235
2236        if (uframes > (ehci->maxframes * 8)) {
2237            skipped_uframes = uframes - (ehci->maxframes * 8);
2238            ehci_update_frindex(ehci, skipped_uframes);
2239            ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;
2240            uframes -= skipped_uframes;
2241            DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);
2242        }
2243
2244        for (i = 0; i < uframes; i++) {
2245            /*
2246             * If we're running behind schedule, we should not catch up
2247             * too fast, as that will make some guests unhappy:
2248             * 1) We must process a minimum of MIN_UFR_PER_TICK frames,
2249             *    otherwise we will never catch up
2250             * 2) Process frames until the guest has requested an irq (IOC)
2251             */
2252            if (i >= MIN_UFR_PER_TICK) {
2253                ehci_commit_irq(ehci);
2254                if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {
2255                    break;
2256                }
2257            }
2258            if (ehci->periodic_sched_active) {
2259                ehci->periodic_sched_active--;
2260            }
2261            ehci_update_frindex(ehci, 1);
2262            if ((ehci->frindex & 7) == 0) {
2263                ehci_advance_periodic_state(ehci);
2264            }
2265            ehci->last_run_ns += UFRAME_TIMER_NS;
2266        }
2267    } else {
2268        ehci->periodic_sched_active = 0;
2269        ehci_update_frindex(ehci, uframes);
2270        ehci->last_run_ns += UFRAME_TIMER_NS * uframes;
2271    }
2272
2273    if (ehci->periodic_sched_active) {
2274        ehci->async_stepdown = 0;
2275    } else if (ehci->async_stepdown < ehci->maxframes / 2) {
2276        ehci->async_stepdown++;
2277    }
2278
2279    /*  Async is not inside loop since it executes everything it can once
2280     *  called
2281     */
2282    if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
2283        need_timer++;
2284        ehci_advance_async_state(ehci);
2285    }
2286
2287    ehci_commit_irq(ehci);
2288    if (ehci->usbsts_pending) {
2289        need_timer++;
2290        ehci->async_stepdown = 0;
2291    }
2292
2293    if (ehci_enabled(ehci) && (ehci->usbintr & USBSTS_FLR)) {
2294        need_timer++;
2295    }
2296
2297    if (need_timer) {
2298        /* If we've raised int, we speed up the timer, so that we quickly
2299         * notice any new packets queued up in response */
2300        if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {
2301            expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 4);
2302            ehci->int_req_by_async = false;
2303        } else {
2304            expire_time = t_now + (get_ticks_per_sec()
2305                               * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);
2306        }
2307        timer_mod(ehci->frame_timer, expire_time);
2308    }
2309}
2310
2311static const MemoryRegionOps ehci_mmio_caps_ops = {
2312    .read = ehci_caps_read,
2313    .valid.min_access_size = 1,
2314    .valid.max_access_size = 4,
2315    .impl.min_access_size = 1,
2316    .impl.max_access_size = 1,
2317    .endianness = DEVICE_LITTLE_ENDIAN,
2318};
2319
2320static const MemoryRegionOps ehci_mmio_opreg_ops = {
2321    .read = ehci_opreg_read,
2322    .write = ehci_opreg_write,
2323    .valid.min_access_size = 4,
2324    .valid.max_access_size = 4,
2325    .endianness = DEVICE_LITTLE_ENDIAN,
2326};
2327
2328static const MemoryRegionOps ehci_mmio_port_ops = {
2329    .read = ehci_port_read,
2330    .write = ehci_port_write,
2331    .valid.min_access_size = 4,
2332    .valid.max_access_size = 4,
2333    .endianness = DEVICE_LITTLE_ENDIAN,
2334};
2335
2336static USBPortOps ehci_port_ops = {
2337    .attach = ehci_attach,
2338    .detach = ehci_detach,
2339    .child_detach = ehci_child_detach,
2340    .wakeup = ehci_wakeup,
2341    .complete = ehci_async_complete_packet,
2342};
2343
2344static USBBusOps ehci_bus_ops_companion = {
2345    .register_companion = ehci_register_companion,
2346    .wakeup_endpoint = ehci_wakeup_endpoint,
2347};
2348static USBBusOps ehci_bus_ops_standalone = {
2349    .wakeup_endpoint = ehci_wakeup_endpoint,
2350};
2351
2352static void usb_ehci_pre_save(void *opaque)
2353{
2354    EHCIState *ehci = opaque;
2355    uint32_t new_frindex;
2356
2357    /* Round down frindex to a multiple of 8 for migration compatibility */
2358    new_frindex = ehci->frindex & ~7;
2359    ehci->last_run_ns -= (ehci->frindex - new_frindex) * UFRAME_TIMER_NS;
2360    ehci->frindex = new_frindex;
2361}
2362
2363static int usb_ehci_post_load(void *opaque, int version_id)
2364{
2365    EHCIState *s = opaque;
2366    int i;
2367
2368    for (i = 0; i < NB_PORTS; i++) {
2369        USBPort *companion = s->companion_ports[i];
2370        if (companion == NULL) {
2371            continue;
2372        }
2373        if (s->portsc[i] & PORTSC_POWNER) {
2374            companion->dev = s->ports[i].dev;
2375        } else {
2376            companion->dev = NULL;
2377        }
2378    }
2379
2380    return 0;
2381}
2382
2383static void usb_ehci_vm_state_change(void *opaque, int running, RunState state)
2384{
2385    EHCIState *ehci = opaque;
2386
2387    /*
2388     * We don't migrate the EHCIQueue-s, instead we rebuild them for the
2389     * schedule in guest memory. We must do the rebuilt ASAP, so that
2390     * USB-devices which have async handled packages have a packet in the
2391     * ep queue to match the completion with.
2392     */
2393    if (state == RUN_STATE_RUNNING) {
2394        ehci_advance_async_state(ehci);
2395    }
2396
2397    /*
2398     * The schedule rebuilt from guest memory could cause the migration dest
2399     * to miss a QH unlink, and fail to cancel packets, since the unlinked QH
2400     * will never have existed on the destination. Therefor we must flush the
2401     * async schedule on savevm to catch any not yet noticed unlinks.
2402     */
2403    if (state == RUN_STATE_SAVE_VM) {
2404        ehci_advance_async_state(ehci);
2405        ehci_queues_rip_unseen(ehci, 1);
2406    }
2407}
2408
2409const VMStateDescription vmstate_ehci = {
2410    .name        = "ehci-core",
2411    .version_id  = 2,
2412    .minimum_version_id  = 1,
2413    .pre_save    = usb_ehci_pre_save,
2414    .post_load   = usb_ehci_post_load,
2415    .fields = (VMStateField[]) {
2416        /* mmio registers */
2417        VMSTATE_UINT32(usbcmd, EHCIState),
2418        VMSTATE_UINT32(usbsts, EHCIState),
2419        VMSTATE_UINT32_V(usbsts_pending, EHCIState, 2),
2420        VMSTATE_UINT32_V(usbsts_frindex, EHCIState, 2),
2421        VMSTATE_UINT32(usbintr, EHCIState),
2422        VMSTATE_UINT32(frindex, EHCIState),
2423        VMSTATE_UINT32(ctrldssegment, EHCIState),
2424        VMSTATE_UINT32(periodiclistbase, EHCIState),
2425        VMSTATE_UINT32(asynclistaddr, EHCIState),
2426        VMSTATE_UINT32(configflag, EHCIState),
2427        VMSTATE_UINT32(portsc[0], EHCIState),
2428        VMSTATE_UINT32(portsc[1], EHCIState),
2429        VMSTATE_UINT32(portsc[2], EHCIState),
2430        VMSTATE_UINT32(portsc[3], EHCIState),
2431        VMSTATE_UINT32(portsc[4], EHCIState),
2432        VMSTATE_UINT32(portsc[5], EHCIState),
2433        /* frame timer */
2434        VMSTATE_TIMER_PTR(frame_timer, EHCIState),
2435        VMSTATE_UINT64(last_run_ns, EHCIState),
2436        VMSTATE_UINT32(async_stepdown, EHCIState),
2437        /* schedule state */
2438        VMSTATE_UINT32(astate, EHCIState),
2439        VMSTATE_UINT32(pstate, EHCIState),
2440        VMSTATE_UINT32(a_fetch_addr, EHCIState),
2441        VMSTATE_UINT32(p_fetch_addr, EHCIState),
2442        VMSTATE_END_OF_LIST()
2443    }
2444};
2445
2446void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp)
2447{
2448    int i;
2449
2450    if (s->portnr > NB_PORTS) {
2451        error_setg(errp, "Too many ports! Max. port number is %d.",
2452                   NB_PORTS);
2453        return;
2454    }
2455
2456    usb_bus_new(&s->bus, sizeof(s->bus), s->companion_enable ?
2457                &ehci_bus_ops_companion : &ehci_bus_ops_standalone, dev);
2458    for (i = 0; i < s->portnr; i++) {
2459        usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops,
2460                          USB_SPEED_MASK_HIGH);
2461        s->ports[i].dev = 0;
2462    }
2463
2464    s->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ehci_frame_timer, s);
2465    s->async_bh = qemu_bh_new(ehci_frame_timer, s);
2466    s->device = dev;
2467
2468    s->vmstate = qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s);
2469}
2470
2471void usb_ehci_unrealize(EHCIState *s, DeviceState *dev, Error **errp)
2472{
2473    trace_usb_ehci_unrealize();
2474
2475    if (s->frame_timer) {
2476        timer_del(s->frame_timer);
2477        timer_free(s->frame_timer);
2478        s->frame_timer = NULL;
2479    }
2480    if (s->async_bh) {
2481        qemu_bh_delete(s->async_bh);
2482    }
2483
2484    ehci_queues_rip_all(s, 0);
2485    ehci_queues_rip_all(s, 1);
2486
2487    memory_region_del_subregion(&s->mem, &s->mem_caps);
2488    memory_region_del_subregion(&s->mem, &s->mem_opreg);
2489    memory_region_del_subregion(&s->mem, &s->mem_ports);
2490
2491    usb_bus_release(&s->bus);
2492
2493    if (s->vmstate) {
2494        qemu_del_vm_change_state_handler(s->vmstate);
2495    }
2496}
2497
2498void usb_ehci_init(EHCIState *s, DeviceState *dev)
2499{
2500    /* 2.2 host controller interface version */
2501    s->caps[0x00] = (uint8_t)(s->opregbase - s->capsbase);
2502    s->caps[0x01] = 0x00;
2503    s->caps[0x02] = 0x00;
2504    s->caps[0x03] = 0x01;        /* HC version */
2505    s->caps[0x04] = s->portnr;   /* Number of downstream ports */
2506    s->caps[0x05] = 0x00;        /* No companion ports at present */
2507    s->caps[0x06] = 0x00;
2508    s->caps[0x07] = 0x00;
2509    s->caps[0x08] = 0x80;        /* We can cache whole frame, no 64-bit */
2510    s->caps[0x0a] = 0x00;
2511    s->caps[0x0b] = 0x00;
2512
2513    QTAILQ_INIT(&s->aqueues);
2514    QTAILQ_INIT(&s->pqueues);
2515    usb_packet_init(&s->ipacket);
2516
2517    memory_region_init(&s->mem, OBJECT(dev), "ehci", MMIO_SIZE);
2518    memory_region_init_io(&s->mem_caps, OBJECT(dev), &ehci_mmio_caps_ops, s,
2519                          "capabilities", CAPA_SIZE);
2520    memory_region_init_io(&s->mem_opreg, OBJECT(dev), &ehci_mmio_opreg_ops, s,
2521                          "operational", s->portscbase);
2522    memory_region_init_io(&s->mem_ports, OBJECT(dev), &ehci_mmio_port_ops, s,
2523                          "ports", 4 * s->portnr);
2524
2525    memory_region_add_subregion(&s->mem, s->capsbase, &s->mem_caps);
2526    memory_region_add_subregion(&s->mem, s->opregbase, &s->mem_opreg);
2527    memory_region_add_subregion(&s->mem, s->opregbase + s->portscbase,
2528                                &s->mem_ports);
2529}
2530
2531/*
2532 * vim: expandtab ts=4
2533 */
2534