qemu/hw/usb/hcd-ohci.c
<<
>>
Prefs
   1/*
   2 * QEMU USB OHCI Emulation
   3 * Copyright (c) 2004 Gianni Tedesco
   4 * Copyright (c) 2006 CodeSourcery
   5 * Copyright (c) 2006 Openedhand Ltd.
   6 *
   7 * This library is free software; you can redistribute it and/or
   8 * modify it under the terms of the GNU Lesser General Public
   9 * License as published by the Free Software Foundation; either
  10 * version 2 of the License, or (at your option) any later version.
  11 *
  12 * This library is distributed in the hope that it will be useful,
  13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15 * Lesser General Public License for more details.
  16 *
  17 * You should have received a copy of the GNU Lesser General Public
  18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  19 *
  20 * TODO:
  21 *  o Isochronous transfers
  22 *  o Allocate bandwidth in frames properly
  23 *  o Disable timers when nothing needs to be done, or remove timer usage
  24 *    all together.
  25 *  o Handle unrecoverable errors properly
  26 *  o BIOS work to boot from USB storage
  27*/
  28
  29#include "hw/hw.h"
  30#include "qemu/timer.h"
  31#include "hw/usb.h"
  32#include "hw/pci/pci.h"
  33#include "hw/sysbus.h"
  34#include "hw/qdev-dma.h"
  35
  36//#define DEBUG_OHCI
  37/* Dump packet contents.  */
  38//#define DEBUG_PACKET
  39//#define DEBUG_ISOCH
  40/* This causes frames to occur 1000x slower */
  41//#define OHCI_TIME_WARP 1
  42
  43#ifdef DEBUG_OHCI
  44#define DPRINTF printf
  45#else
  46#define DPRINTF(...)
  47#endif
  48
  49/* Number of Downstream Ports on the root hub.  */
  50
  51#define OHCI_MAX_PORTS 15
  52
  53static int64_t usb_frame_time;
  54static int64_t usb_bit_time;
  55
  56typedef struct OHCIPort {
  57    USBPort port;
  58    uint32_t ctrl;
  59} OHCIPort;
  60
  61typedef struct {
  62    USBBus bus;
  63    qemu_irq irq;
  64    MemoryRegion mem;
  65    DMAContext *dma;
  66    int num_ports;
  67    const char *name;
  68
  69    QEMUTimer *eof_timer;
  70    int64_t sof_time;
  71
  72    /* OHCI state */
  73    /* Control partition */
  74    uint32_t ctl, status;
  75    uint32_t intr_status;
  76    uint32_t intr;
  77
  78    /* memory pointer partition */
  79    uint32_t hcca;
  80    uint32_t ctrl_head, ctrl_cur;
  81    uint32_t bulk_head, bulk_cur;
  82    uint32_t per_cur;
  83    uint32_t done;
  84    int done_count;
  85
  86    /* Frame counter partition */
  87    uint32_t fsmps:15;
  88    uint32_t fit:1;
  89    uint32_t fi:14;
  90    uint32_t frt:1;
  91    uint16_t frame_number;
  92    uint16_t padding;
  93    uint32_t pstart;
  94    uint32_t lst;
  95
  96    /* Root Hub partition */
  97    uint32_t rhdesc_a, rhdesc_b;
  98    uint32_t rhstatus;
  99    OHCIPort rhport[OHCI_MAX_PORTS];
 100
 101    /* PXA27x Non-OHCI events */
 102    uint32_t hstatus;
 103    uint32_t hmask;
 104    uint32_t hreset;
 105    uint32_t htest;
 106
 107    /* SM501 local memory offset */
 108    dma_addr_t localmem_base;
 109
 110    /* Active packets.  */
 111    uint32_t old_ctl;
 112    USBPacket usb_packet;
 113    uint8_t usb_buf[8192];
 114    uint32_t async_td;
 115    int async_complete;
 116
 117} OHCIState;
 118
 119/* Host Controller Communications Area */
 120struct ohci_hcca {
 121    uint32_t intr[32];
 122    uint16_t frame, pad;
 123    uint32_t done;
 124};
 125#define HCCA_WRITEBACK_OFFSET   offsetof(struct ohci_hcca, frame)
 126#define HCCA_WRITEBACK_SIZE     8 /* frame, pad, done */
 127
 128#define ED_WBACK_OFFSET offsetof(struct ohci_ed, head)
 129#define ED_WBACK_SIZE   4
 130
 131static void ohci_bus_stop(OHCIState *ohci);
 132static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev);
 133
 134/* Bitfields for the first word of an Endpoint Desciptor.  */
 135#define OHCI_ED_FA_SHIFT  0
 136#define OHCI_ED_FA_MASK   (0x7f<<OHCI_ED_FA_SHIFT)
 137#define OHCI_ED_EN_SHIFT  7
 138#define OHCI_ED_EN_MASK   (0xf<<OHCI_ED_EN_SHIFT)
 139#define OHCI_ED_D_SHIFT   11
 140#define OHCI_ED_D_MASK    (3<<OHCI_ED_D_SHIFT)
 141#define OHCI_ED_S         (1<<13)
 142#define OHCI_ED_K         (1<<14)
 143#define OHCI_ED_F         (1<<15)
 144#define OHCI_ED_MPS_SHIFT 16
 145#define OHCI_ED_MPS_MASK  (0x7ff<<OHCI_ED_MPS_SHIFT)
 146
 147/* Flags in the head field of an Endpoint Desciptor.  */
 148#define OHCI_ED_H         1
 149#define OHCI_ED_C         2
 150
 151/* Bitfields for the first word of a Transfer Desciptor.  */
 152#define OHCI_TD_R         (1<<18)
 153#define OHCI_TD_DP_SHIFT  19
 154#define OHCI_TD_DP_MASK   (3<<OHCI_TD_DP_SHIFT)
 155#define OHCI_TD_DI_SHIFT  21
 156#define OHCI_TD_DI_MASK   (7<<OHCI_TD_DI_SHIFT)
 157#define OHCI_TD_T0        (1<<24)
 158#define OHCI_TD_T1        (1<<25)
 159#define OHCI_TD_EC_SHIFT  26
 160#define OHCI_TD_EC_MASK   (3<<OHCI_TD_EC_SHIFT)
 161#define OHCI_TD_CC_SHIFT  28
 162#define OHCI_TD_CC_MASK   (0xf<<OHCI_TD_CC_SHIFT)
 163
 164/* Bitfields for the first word of an Isochronous Transfer Desciptor.  */
 165/* CC & DI - same as in the General Transfer Desciptor */
 166#define OHCI_TD_SF_SHIFT  0
 167#define OHCI_TD_SF_MASK   (0xffff<<OHCI_TD_SF_SHIFT)
 168#define OHCI_TD_FC_SHIFT  24
 169#define OHCI_TD_FC_MASK   (7<<OHCI_TD_FC_SHIFT)
 170
 171/* Isochronous Transfer Desciptor - Offset / PacketStatusWord */
 172#define OHCI_TD_PSW_CC_SHIFT 12
 173#define OHCI_TD_PSW_CC_MASK  (0xf<<OHCI_TD_PSW_CC_SHIFT)
 174#define OHCI_TD_PSW_SIZE_SHIFT 0
 175#define OHCI_TD_PSW_SIZE_MASK  (0xfff<<OHCI_TD_PSW_SIZE_SHIFT)
 176
 177#define OHCI_PAGE_MASK    0xfffff000
 178#define OHCI_OFFSET_MASK  0xfff
 179
 180#define OHCI_DPTR_MASK    0xfffffff0
 181
 182#define OHCI_BM(val, field) \
 183  (((val) & OHCI_##field##_MASK) >> OHCI_##field##_SHIFT)
 184
 185#define OHCI_SET_BM(val, field, newval) do { \
 186    val &= ~OHCI_##field##_MASK; \
 187    val |= ((newval) << OHCI_##field##_SHIFT) & OHCI_##field##_MASK; \
 188    } while(0)
 189
 190/* endpoint descriptor */
 191struct ohci_ed {
 192    uint32_t flags;
 193    uint32_t tail;
 194    uint32_t head;
 195    uint32_t next;
 196};
 197
 198/* General transfer descriptor */
 199struct ohci_td {
 200    uint32_t flags;
 201    uint32_t cbp;
 202    uint32_t next;
 203    uint32_t be;
 204};
 205
 206/* Isochronous transfer descriptor */
 207struct ohci_iso_td {
 208    uint32_t flags;
 209    uint32_t bp;
 210    uint32_t next;
 211    uint32_t be;
 212    uint16_t offset[8];
 213};
 214
 215#define USB_HZ                      12000000
 216
 217/* OHCI Local stuff */
 218#define OHCI_CTL_CBSR         ((1<<0)|(1<<1))
 219#define OHCI_CTL_PLE          (1<<2)
 220#define OHCI_CTL_IE           (1<<3)
 221#define OHCI_CTL_CLE          (1<<4)
 222#define OHCI_CTL_BLE          (1<<5)
 223#define OHCI_CTL_HCFS         ((1<<6)|(1<<7))
 224#define  OHCI_USB_RESET       0x00
 225#define  OHCI_USB_RESUME      0x40
 226#define  OHCI_USB_OPERATIONAL 0x80
 227#define  OHCI_USB_SUSPEND     0xc0
 228#define OHCI_CTL_IR           (1<<8)
 229#define OHCI_CTL_RWC          (1<<9)
 230#define OHCI_CTL_RWE          (1<<10)
 231
 232#define OHCI_STATUS_HCR       (1<<0)
 233#define OHCI_STATUS_CLF       (1<<1)
 234#define OHCI_STATUS_BLF       (1<<2)
 235#define OHCI_STATUS_OCR       (1<<3)
 236#define OHCI_STATUS_SOC       ((1<<6)|(1<<7))
 237
 238#define OHCI_INTR_SO          (1<<0) /* Scheduling overrun */
 239#define OHCI_INTR_WD          (1<<1) /* HcDoneHead writeback */
 240#define OHCI_INTR_SF          (1<<2) /* Start of frame */
 241#define OHCI_INTR_RD          (1<<3) /* Resume detect */
 242#define OHCI_INTR_UE          (1<<4) /* Unrecoverable error */
 243#define OHCI_INTR_FNO         (1<<5) /* Frame number overflow */
 244#define OHCI_INTR_RHSC        (1<<6) /* Root hub status change */
 245#define OHCI_INTR_OC          (1<<30) /* Ownership change */
 246#define OHCI_INTR_MIE         (1<<31) /* Master Interrupt Enable */
 247
 248#define OHCI_HCCA_SIZE        0x100
 249#define OHCI_HCCA_MASK        0xffffff00
 250
 251#define OHCI_EDPTR_MASK       0xfffffff0
 252
 253#define OHCI_FMI_FI           0x00003fff
 254#define OHCI_FMI_FSMPS        0xffff0000
 255#define OHCI_FMI_FIT          0x80000000
 256
 257#define OHCI_FR_RT            (1<<31)
 258
 259#define OHCI_LS_THRESH        0x628
 260
 261#define OHCI_RHA_RW_MASK      0x00000000 /* Mask of supported features.  */
 262#define OHCI_RHA_PSM          (1<<8)
 263#define OHCI_RHA_NPS          (1<<9)
 264#define OHCI_RHA_DT           (1<<10)
 265#define OHCI_RHA_OCPM         (1<<11)
 266#define OHCI_RHA_NOCP         (1<<12)
 267#define OHCI_RHA_POTPGT_MASK  0xff000000
 268
 269#define OHCI_RHS_LPS          (1<<0)
 270#define OHCI_RHS_OCI          (1<<1)
 271#define OHCI_RHS_DRWE         (1<<15)
 272#define OHCI_RHS_LPSC         (1<<16)
 273#define OHCI_RHS_OCIC         (1<<17)
 274#define OHCI_RHS_CRWE         (1<<31)
 275
 276#define OHCI_PORT_CCS         (1<<0)
 277#define OHCI_PORT_PES         (1<<1)
 278#define OHCI_PORT_PSS         (1<<2)
 279#define OHCI_PORT_POCI        (1<<3)
 280#define OHCI_PORT_PRS         (1<<4)
 281#define OHCI_PORT_PPS         (1<<8)
 282#define OHCI_PORT_LSDA        (1<<9)
 283#define OHCI_PORT_CSC         (1<<16)
 284#define OHCI_PORT_PESC        (1<<17)
 285#define OHCI_PORT_PSSC        (1<<18)
 286#define OHCI_PORT_OCIC        (1<<19)
 287#define OHCI_PORT_PRSC        (1<<20)
 288#define OHCI_PORT_WTC         (OHCI_PORT_CSC|OHCI_PORT_PESC|OHCI_PORT_PSSC \
 289                               |OHCI_PORT_OCIC|OHCI_PORT_PRSC)
 290
 291#define OHCI_TD_DIR_SETUP     0x0
 292#define OHCI_TD_DIR_OUT       0x1
 293#define OHCI_TD_DIR_IN        0x2
 294#define OHCI_TD_DIR_RESERVED  0x3
 295
 296#define OHCI_CC_NOERROR             0x0
 297#define OHCI_CC_CRC                 0x1
 298#define OHCI_CC_BITSTUFFING         0x2
 299#define OHCI_CC_DATATOGGLEMISMATCH  0x3
 300#define OHCI_CC_STALL               0x4
 301#define OHCI_CC_DEVICENOTRESPONDING 0x5
 302#define OHCI_CC_PIDCHECKFAILURE     0x6
 303#define OHCI_CC_UNDEXPETEDPID       0x7
 304#define OHCI_CC_DATAOVERRUN         0x8
 305#define OHCI_CC_DATAUNDERRUN        0x9
 306#define OHCI_CC_BUFFEROVERRUN       0xc
 307#define OHCI_CC_BUFFERUNDERRUN      0xd
 308
 309#define OHCI_HRESET_FSBIR       (1 << 0)
 310
 311/* Update IRQ levels */
 312static inline void ohci_intr_update(OHCIState *ohci)
 313{
 314    int level = 0;
 315
 316    if ((ohci->intr & OHCI_INTR_MIE) &&
 317        (ohci->intr_status & ohci->intr))
 318        level = 1;
 319
 320    qemu_set_irq(ohci->irq, level);
 321}
 322
 323/* Set an interrupt */
 324static inline void ohci_set_interrupt(OHCIState *ohci, uint32_t intr)
 325{
 326    ohci->intr_status |= intr;
 327    ohci_intr_update(ohci);
 328}
 329
 330/* Attach or detach a device on a root hub port.  */
 331static void ohci_attach(USBPort *port1)
 332{
 333    OHCIState *s = port1->opaque;
 334    OHCIPort *port = &s->rhport[port1->index];
 335    uint32_t old_state = port->ctrl;
 336
 337    /* set connect status */
 338    port->ctrl |= OHCI_PORT_CCS | OHCI_PORT_CSC;
 339
 340    /* update speed */
 341    if (port->port.dev->speed == USB_SPEED_LOW) {
 342        port->ctrl |= OHCI_PORT_LSDA;
 343    } else {
 344        port->ctrl &= ~OHCI_PORT_LSDA;
 345    }
 346
 347    /* notify of remote-wakeup */
 348    if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND) {
 349        ohci_set_interrupt(s, OHCI_INTR_RD);
 350    }
 351
 352    DPRINTF("usb-ohci: Attached port %d\n", port1->index);
 353
 354    if (old_state != port->ctrl) {
 355        ohci_set_interrupt(s, OHCI_INTR_RHSC);
 356    }
 357}
 358
 359static void ohci_detach(USBPort *port1)
 360{
 361    OHCIState *s = port1->opaque;
 362    OHCIPort *port = &s->rhport[port1->index];
 363    uint32_t old_state = port->ctrl;
 364
 365    ohci_async_cancel_device(s, port1->dev);
 366
 367    /* set connect status */
 368    if (port->ctrl & OHCI_PORT_CCS) {
 369        port->ctrl &= ~OHCI_PORT_CCS;
 370        port->ctrl |= OHCI_PORT_CSC;
 371    }
 372    /* disable port */
 373    if (port->ctrl & OHCI_PORT_PES) {
 374        port->ctrl &= ~OHCI_PORT_PES;
 375        port->ctrl |= OHCI_PORT_PESC;
 376    }
 377    DPRINTF("usb-ohci: Detached port %d\n", port1->index);
 378
 379    if (old_state != port->ctrl) {
 380        ohci_set_interrupt(s, OHCI_INTR_RHSC);
 381    }
 382}
 383
 384static void ohci_wakeup(USBPort *port1)
 385{
 386    OHCIState *s = port1->opaque;
 387    OHCIPort *port = &s->rhport[port1->index];
 388    uint32_t intr = 0;
 389    if (port->ctrl & OHCI_PORT_PSS) {
 390        DPRINTF("usb-ohci: port %d: wakeup\n", port1->index);
 391        port->ctrl |= OHCI_PORT_PSSC;
 392        port->ctrl &= ~OHCI_PORT_PSS;
 393        intr = OHCI_INTR_RHSC;
 394    }
 395    /* Note that the controller can be suspended even if this port is not */
 396    if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND) {
 397        DPRINTF("usb-ohci: remote-wakeup: SUSPEND->RESUME\n");
 398        /* This is the one state transition the controller can do by itself */
 399        s->ctl &= ~OHCI_CTL_HCFS;
 400        s->ctl |= OHCI_USB_RESUME;
 401        /* In suspend mode only ResumeDetected is possible, not RHSC:
 402         * see the OHCI spec 5.1.2.3.
 403         */
 404        intr = OHCI_INTR_RD;
 405    }
 406    ohci_set_interrupt(s, intr);
 407}
 408
 409static void ohci_child_detach(USBPort *port1, USBDevice *child)
 410{
 411    OHCIState *s = port1->opaque;
 412
 413    ohci_async_cancel_device(s, child);
 414}
 415
 416static USBDevice *ohci_find_device(OHCIState *ohci, uint8_t addr)
 417{
 418    USBDevice *dev;
 419    int i;
 420
 421    for (i = 0; i < ohci->num_ports; i++) {
 422        if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0) {
 423            continue;
 424        }
 425        dev = usb_find_device(&ohci->rhport[i].port, addr);
 426        if (dev != NULL) {
 427            return dev;
 428        }
 429    }
 430    return NULL;
 431}
 432
 433static void ohci_stop_endpoints(OHCIState *ohci)
 434{
 435    USBDevice *dev;
 436    int i, j;
 437
 438    for (i = 0; i < ohci->num_ports; i++) {
 439        dev = ohci->rhport[i].port.dev;
 440        if (dev && dev->attached) {
 441            usb_device_ep_stopped(dev, &dev->ep_ctl);
 442            for (j = 0; j < USB_MAX_ENDPOINTS; j++) {
 443                usb_device_ep_stopped(dev, &dev->ep_in[j]);
 444                usb_device_ep_stopped(dev, &dev->ep_out[j]);
 445            }
 446        }
 447    }
 448}
 449
 450/* Reset the controller */
 451static void ohci_reset(void *opaque)
 452{
 453    OHCIState *ohci = opaque;
 454    OHCIPort *port;
 455    int i;
 456
 457    ohci_bus_stop(ohci);
 458    ohci->ctl = 0;
 459    ohci->old_ctl = 0;
 460    ohci->status = 0;
 461    ohci->intr_status = 0;
 462    ohci->intr = OHCI_INTR_MIE;
 463
 464    ohci->hcca = 0;
 465    ohci->ctrl_head = ohci->ctrl_cur = 0;
 466    ohci->bulk_head = ohci->bulk_cur = 0;
 467    ohci->per_cur = 0;
 468    ohci->done = 0;
 469    ohci->done_count = 7;
 470
 471    /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?
 472     * I took the value linux sets ...
 473     */
 474    ohci->fsmps = 0x2778;
 475    ohci->fi = 0x2edf;
 476    ohci->fit = 0;
 477    ohci->frt = 0;
 478    ohci->frame_number = 0;
 479    ohci->pstart = 0;
 480    ohci->lst = OHCI_LS_THRESH;
 481
 482    ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;
 483    ohci->rhdesc_b = 0x0; /* Impl. specific */
 484    ohci->rhstatus = 0;
 485
 486    for (i = 0; i < ohci->num_ports; i++)
 487      {
 488        port = &ohci->rhport[i];
 489        port->ctrl = 0;
 490        if (port->port.dev && port->port.dev->attached) {
 491            usb_port_reset(&port->port);
 492        }
 493      }
 494    if (ohci->async_td) {
 495        usb_cancel_packet(&ohci->usb_packet);
 496        ohci->async_td = 0;
 497    }
 498    ohci_stop_endpoints(ohci);
 499    DPRINTF("usb-ohci: Reset %s\n", ohci->name);
 500}
 501
 502/* Get an array of dwords from main memory */
 503static inline int get_dwords(OHCIState *ohci,
 504                             dma_addr_t addr, uint32_t *buf, int num)
 505{
 506    int i;
 507
 508    addr += ohci->localmem_base;
 509
 510    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 511        dma_memory_read(ohci->dma, addr, buf, sizeof(*buf));
 512        *buf = le32_to_cpu(*buf);
 513    }
 514
 515    return 1;
 516}
 517
 518/* Put an array of dwords in to main memory */
 519static inline int put_dwords(OHCIState *ohci,
 520                             dma_addr_t addr, uint32_t *buf, int num)
 521{
 522    int i;
 523
 524    addr += ohci->localmem_base;
 525
 526    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 527        uint32_t tmp = cpu_to_le32(*buf);
 528        dma_memory_write(ohci->dma, addr, &tmp, sizeof(tmp));
 529    }
 530
 531    return 1;
 532}
 533
 534/* Get an array of words from main memory */
 535static inline int get_words(OHCIState *ohci,
 536                            dma_addr_t addr, uint16_t *buf, int num)
 537{
 538    int i;
 539
 540    addr += ohci->localmem_base;
 541
 542    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 543        dma_memory_read(ohci->dma, addr, buf, sizeof(*buf));
 544        *buf = le16_to_cpu(*buf);
 545    }
 546
 547    return 1;
 548}
 549
 550/* Put an array of words in to main memory */
 551static inline int put_words(OHCIState *ohci,
 552                            dma_addr_t addr, uint16_t *buf, int num)
 553{
 554    int i;
 555
 556    addr += ohci->localmem_base;
 557
 558    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
 559        uint16_t tmp = cpu_to_le16(*buf);
 560        dma_memory_write(ohci->dma, addr, &tmp, sizeof(tmp));
 561    }
 562
 563    return 1;
 564}
 565
 566static inline int ohci_read_ed(OHCIState *ohci,
 567                               dma_addr_t addr, struct ohci_ed *ed)
 568{
 569    return get_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
 570}
 571
 572static inline int ohci_read_td(OHCIState *ohci,
 573                               dma_addr_t addr, struct ohci_td *td)
 574{
 575    return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
 576}
 577
 578static inline int ohci_read_iso_td(OHCIState *ohci,
 579                                   dma_addr_t addr, struct ohci_iso_td *td)
 580{
 581    return (get_dwords(ohci, addr, (uint32_t *)td, 4) &&
 582            get_words(ohci, addr + 16, td->offset, 8));
 583}
 584
 585static inline int ohci_read_hcca(OHCIState *ohci,
 586                                 dma_addr_t addr, struct ohci_hcca *hcca)
 587{
 588    dma_memory_read(ohci->dma, addr + ohci->localmem_base, hcca, sizeof(*hcca));
 589    return 1;
 590}
 591
 592static inline int ohci_put_ed(OHCIState *ohci,
 593                              dma_addr_t addr, struct ohci_ed *ed)
 594{
 595    /* ed->tail is under control of the HCD.
 596     * Since just ed->head is changed by HC, just write back this
 597     */
 598
 599    return put_dwords(ohci, addr + ED_WBACK_OFFSET,
 600                      (uint32_t *)((char *)ed + ED_WBACK_OFFSET),
 601                      ED_WBACK_SIZE >> 2);
 602}
 603
 604static inline int ohci_put_td(OHCIState *ohci,
 605                              dma_addr_t addr, struct ohci_td *td)
 606{
 607    return put_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
 608}
 609
 610static inline int ohci_put_iso_td(OHCIState *ohci,
 611                                  dma_addr_t addr, struct ohci_iso_td *td)
 612{
 613    return (put_dwords(ohci, addr, (uint32_t *)td, 4) &&
 614            put_words(ohci, addr + 16, td->offset, 8));
 615}
 616
 617static inline int ohci_put_hcca(OHCIState *ohci,
 618                                dma_addr_t addr, struct ohci_hcca *hcca)
 619{
 620    dma_memory_write(ohci->dma,
 621                     addr + ohci->localmem_base + HCCA_WRITEBACK_OFFSET,
 622                     (char *)hcca + HCCA_WRITEBACK_OFFSET,
 623                     HCCA_WRITEBACK_SIZE);
 624    return 1;
 625}
 626
 627/* Read/Write the contents of a TD from/to main memory.  */
 628static void ohci_copy_td(OHCIState *ohci, struct ohci_td *td,
 629                         uint8_t *buf, int len, DMADirection dir)
 630{
 631    dma_addr_t ptr, n;
 632
 633    ptr = td->cbp;
 634    n = 0x1000 - (ptr & 0xfff);
 635    if (n > len)
 636        n = len;
 637    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, n, dir);
 638    if (n == len)
 639        return;
 640    ptr = td->be & ~0xfffu;
 641    buf += n;
 642    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, len - n, dir);
 643}
 644
 645/* Read/Write the contents of an ISO TD from/to main memory.  */
 646static void ohci_copy_iso_td(OHCIState *ohci,
 647                             uint32_t start_addr, uint32_t end_addr,
 648                             uint8_t *buf, int len, DMADirection dir)
 649{
 650    dma_addr_t ptr, n;
 651
 652    ptr = start_addr;
 653    n = 0x1000 - (ptr & 0xfff);
 654    if (n > len)
 655        n = len;
 656    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, n, dir);
 657    if (n == len)
 658        return;
 659    ptr = end_addr & ~0xfffu;
 660    buf += n;
 661    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, len - n, dir);
 662}
 663
 664static void ohci_process_lists(OHCIState *ohci, int completion);
 665
 666static void ohci_async_complete_packet(USBPort *port, USBPacket *packet)
 667{
 668    OHCIState *ohci = container_of(packet, OHCIState, usb_packet);
 669#ifdef DEBUG_PACKET
 670    DPRINTF("Async packet complete\n");
 671#endif
 672    ohci->async_complete = 1;
 673    ohci_process_lists(ohci, 1);
 674}
 675
 676#define USUB(a, b) ((int16_t)((uint16_t)(a) - (uint16_t)(b)))
 677
 678static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
 679                               int completion)
 680{
 681    int dir;
 682    size_t len = 0;
 683#ifdef DEBUG_ISOCH
 684    const char *str = NULL;
 685#endif
 686    int pid;
 687    int ret;
 688    int i;
 689    USBDevice *dev;
 690    USBEndpoint *ep;
 691    struct ohci_iso_td iso_td;
 692    uint32_t addr;
 693    uint16_t starting_frame;
 694    int16_t relative_frame_number;
 695    int frame_count;
 696    uint32_t start_offset, next_offset, end_offset = 0;
 697    uint32_t start_addr, end_addr;
 698
 699    addr = ed->head & OHCI_DPTR_MASK;
 700
 701    if (!ohci_read_iso_td(ohci, addr, &iso_td)) {
 702        printf("usb-ohci: ISO_TD read error at %x\n", addr);
 703        return 0;
 704    }
 705
 706    starting_frame = OHCI_BM(iso_td.flags, TD_SF);
 707    frame_count = OHCI_BM(iso_td.flags, TD_FC);
 708    relative_frame_number = USUB(ohci->frame_number, starting_frame); 
 709
 710#ifdef DEBUG_ISOCH
 711    printf("--- ISO_TD ED head 0x%.8x tailp 0x%.8x\n"
 712           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
 713           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
 714           "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
 715           "frame_number 0x%.8x starting_frame 0x%.8x\n"
 716           "frame_count  0x%.8x relative %d\n"
 717           "di 0x%.8x cc 0x%.8x\n",
 718           ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
 719           iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
 720           iso_td.offset[0], iso_td.offset[1], iso_td.offset[2], iso_td.offset[3],
 721           iso_td.offset[4], iso_td.offset[5], iso_td.offset[6], iso_td.offset[7],
 722           ohci->frame_number, starting_frame, 
 723           frame_count, relative_frame_number,         
 724           OHCI_BM(iso_td.flags, TD_DI), OHCI_BM(iso_td.flags, TD_CC));
 725#endif
 726
 727    if (relative_frame_number < 0) {
 728        DPRINTF("usb-ohci: ISO_TD R=%d < 0\n", relative_frame_number);
 729        return 1;
 730    } else if (relative_frame_number > frame_count) {
 731        /* ISO TD expired - retire the TD to the Done Queue and continue with
 732           the next ISO TD of the same ED */
 733        DPRINTF("usb-ohci: ISO_TD R=%d > FC=%d\n", relative_frame_number, 
 734               frame_count);
 735        OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
 736        ed->head &= ~OHCI_DPTR_MASK;
 737        ed->head |= (iso_td.next & OHCI_DPTR_MASK);
 738        iso_td.next = ohci->done;
 739        ohci->done = addr;
 740        i = OHCI_BM(iso_td.flags, TD_DI);
 741        if (i < ohci->done_count)
 742            ohci->done_count = i;
 743        ohci_put_iso_td(ohci, addr, &iso_td);
 744        return 0;
 745    }
 746
 747    dir = OHCI_BM(ed->flags, ED_D);
 748    switch (dir) {
 749    case OHCI_TD_DIR_IN:
 750#ifdef DEBUG_ISOCH
 751        str = "in";
 752#endif
 753        pid = USB_TOKEN_IN;
 754        break;
 755    case OHCI_TD_DIR_OUT:
 756#ifdef DEBUG_ISOCH
 757        str = "out";
 758#endif
 759        pid = USB_TOKEN_OUT;
 760        break;
 761    case OHCI_TD_DIR_SETUP:
 762#ifdef DEBUG_ISOCH
 763        str = "setup";
 764#endif
 765        pid = USB_TOKEN_SETUP;
 766        break;
 767    default:
 768        printf("usb-ohci: Bad direction %d\n", dir);
 769        return 1;
 770    }
 771
 772    if (!iso_td.bp || !iso_td.be) {
 773        printf("usb-ohci: ISO_TD bp 0x%.8x be 0x%.8x\n", iso_td.bp, iso_td.be);
 774        return 1;
 775    }
 776
 777    start_offset = iso_td.offset[relative_frame_number];
 778    next_offset = iso_td.offset[relative_frame_number + 1];
 779
 780    if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) || 
 781        ((relative_frame_number < frame_count) && 
 782         !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
 783        printf("usb-ohci: ISO_TD cc != not accessed 0x%.8x 0x%.8x\n",
 784               start_offset, next_offset);
 785        return 1;
 786    }
 787
 788    if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
 789        printf("usb-ohci: ISO_TD start_offset=0x%.8x > next_offset=0x%.8x\n",
 790                start_offset, next_offset);
 791        return 1;
 792    }
 793
 794    if ((start_offset & 0x1000) == 0) {
 795        start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
 796            (start_offset & OHCI_OFFSET_MASK);
 797    } else {
 798        start_addr = (iso_td.be & OHCI_PAGE_MASK) |
 799            (start_offset & OHCI_OFFSET_MASK);
 800    }
 801
 802    if (relative_frame_number < frame_count) {
 803        end_offset = next_offset - 1;
 804        if ((end_offset & 0x1000) == 0) {
 805            end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
 806                (end_offset & OHCI_OFFSET_MASK);
 807        } else {
 808            end_addr = (iso_td.be & OHCI_PAGE_MASK) |
 809                (end_offset & OHCI_OFFSET_MASK);
 810        }
 811    } else {
 812        /* Last packet in the ISO TD */
 813        end_addr = iso_td.be;
 814    }
 815
 816    if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
 817        len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
 818            - (start_addr & OHCI_OFFSET_MASK);
 819    } else {
 820        len = end_addr - start_addr + 1;
 821    }
 822
 823    if (len && dir != OHCI_TD_DIR_IN) {
 824        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
 825                         DMA_DIRECTION_TO_DEVICE);
 826    }
 827
 828    if (!completion) {
 829        bool int_req = relative_frame_number == frame_count &&
 830                       OHCI_BM(iso_td.flags, TD_DI) == 0;
 831        dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
 832        ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
 833        usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
 834        usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
 835        usb_handle_packet(dev, &ohci->usb_packet);
 836        if (ohci->usb_packet.status == USB_RET_ASYNC) {
 837            usb_device_flush_ep_queue(dev, ep);
 838            return 1;
 839        }
 840    }
 841    if (ohci->usb_packet.status == USB_RET_SUCCESS) {
 842        ret = ohci->usb_packet.actual_length;
 843    } else {
 844        ret = ohci->usb_packet.status;
 845    }
 846
 847#ifdef DEBUG_ISOCH
 848    printf("so 0x%.8x eo 0x%.8x\nsa 0x%.8x ea 0x%.8x\ndir %s len %zu ret %d\n",
 849           start_offset, end_offset, start_addr, end_addr, str, len, ret);
 850#endif
 851
 852    /* Writeback */
 853    if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
 854        /* IN transfer succeeded */
 855        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
 856                         DMA_DIRECTION_FROM_DEVICE);
 857        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 858                    OHCI_CC_NOERROR);
 859        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
 860    } else if (dir == OHCI_TD_DIR_OUT && ret == len) {
 861        /* OUT transfer succeeded */
 862        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 863                    OHCI_CC_NOERROR);
 864        OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
 865    } else {
 866        if (ret > (ssize_t) len) {
 867            printf("usb-ohci: DataOverrun %d > %zu\n", ret, len);
 868            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 869                        OHCI_CC_DATAOVERRUN);
 870            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
 871                        len);
 872        } else if (ret >= 0) {
 873            printf("usb-ohci: DataUnderrun %d\n", ret);
 874            OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 875                        OHCI_CC_DATAUNDERRUN);
 876        } else {
 877            switch (ret) {
 878            case USB_RET_IOERROR:
 879            case USB_RET_NODEV:
 880                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 881                            OHCI_CC_DEVICENOTRESPONDING);
 882                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
 883                            0);
 884                break;
 885            case USB_RET_NAK:
 886            case USB_RET_STALL:
 887                printf("usb-ohci: got NAK/STALL %d\n", ret);
 888                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 889                            OHCI_CC_STALL);
 890                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
 891                            0);
 892                break;
 893            default:
 894                printf("usb-ohci: Bad device response %d\n", ret);
 895                OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
 896                            OHCI_CC_UNDEXPETEDPID);
 897                break;
 898            }
 899        }
 900    }
 901
 902    if (relative_frame_number == frame_count) {
 903        /* Last data packet of ISO TD - retire the TD to the Done Queue */
 904        OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
 905        ed->head &= ~OHCI_DPTR_MASK;
 906        ed->head |= (iso_td.next & OHCI_DPTR_MASK);
 907        iso_td.next = ohci->done;
 908        ohci->done = addr;
 909        i = OHCI_BM(iso_td.flags, TD_DI);
 910        if (i < ohci->done_count)
 911            ohci->done_count = i;
 912    }
 913    ohci_put_iso_td(ohci, addr, &iso_td);
 914    return 1;
 915}
 916
 917/* Service a transport descriptor.
 918   Returns nonzero to terminate processing of this endpoint.  */
 919
 920static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
 921{
 922    int dir;
 923    size_t len = 0, pktlen = 0;
 924#ifdef DEBUG_PACKET
 925    const char *str = NULL;
 926#endif
 927    int pid;
 928    int ret;
 929    int i;
 930    USBDevice *dev;
 931    USBEndpoint *ep;
 932    struct ohci_td td;
 933    uint32_t addr;
 934    int flag_r;
 935    int completion;
 936
 937    addr = ed->head & OHCI_DPTR_MASK;
 938    /* See if this TD has already been submitted to the device.  */
 939    completion = (addr == ohci->async_td);
 940    if (completion && !ohci->async_complete) {
 941#ifdef DEBUG_PACKET
 942        DPRINTF("Skipping async TD\n");
 943#endif
 944        return 1;
 945    }
 946    if (!ohci_read_td(ohci, addr, &td)) {
 947        fprintf(stderr, "usb-ohci: TD read error at %x\n", addr);
 948        return 0;
 949    }
 950
 951    dir = OHCI_BM(ed->flags, ED_D);
 952    switch (dir) {
 953    case OHCI_TD_DIR_OUT:
 954    case OHCI_TD_DIR_IN:
 955        /* Same value.  */
 956        break;
 957    default:
 958        dir = OHCI_BM(td.flags, TD_DP);
 959        break;
 960    }
 961
 962    switch (dir) {
 963    case OHCI_TD_DIR_IN:
 964#ifdef DEBUG_PACKET
 965        str = "in";
 966#endif
 967        pid = USB_TOKEN_IN;
 968        break;
 969    case OHCI_TD_DIR_OUT:
 970#ifdef DEBUG_PACKET
 971        str = "out";
 972#endif
 973        pid = USB_TOKEN_OUT;
 974        break;
 975    case OHCI_TD_DIR_SETUP:
 976#ifdef DEBUG_PACKET
 977        str = "setup";
 978#endif
 979        pid = USB_TOKEN_SETUP;
 980        break;
 981    default:
 982        fprintf(stderr, "usb-ohci: Bad direction\n");
 983        return 1;
 984    }
 985    if (td.cbp && td.be) {
 986        if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {
 987            len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);
 988        } else {
 989            len = (td.be - td.cbp) + 1;
 990        }
 991
 992        pktlen = len;
 993        if (len && dir != OHCI_TD_DIR_IN) {
 994            /* The endpoint may not allow us to transfer it all now */
 995            pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;
 996            if (pktlen > len) {
 997                pktlen = len;
 998            }
 999            if (!completion) {
1000                ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen,
1001                             DMA_DIRECTION_TO_DEVICE);
1002            }
1003        }
1004    }
1005
1006    flag_r = (td.flags & OHCI_TD_R) != 0;
1007#ifdef DEBUG_PACKET
1008    DPRINTF(" TD @ 0x%.8x %" PRId64 " of %" PRId64
1009            " bytes %s r=%d cbp=0x%.8x be=0x%.8x\n",
1010            addr, (int64_t)pktlen, (int64_t)len, str, flag_r, td.cbp, td.be);
1011
1012    if (pktlen > 0 && dir != OHCI_TD_DIR_IN) {
1013        DPRINTF("  data:");
1014        for (i = 0; i < pktlen; i++) {
1015            printf(" %.2x", ohci->usb_buf[i]);
1016        }
1017        DPRINTF("\n");
1018    }
1019#endif
1020    if (completion) {
1021        ohci->async_td = 0;
1022        ohci->async_complete = 0;
1023    } else {
1024        if (ohci->async_td) {
1025            /* ??? The hardware should allow one active packet per
1026               endpoint.  We only allow one active packet per controller.
1027               This should be sufficient as long as devices respond in a
1028               timely manner.
1029            */
1030#ifdef DEBUG_PACKET
1031            DPRINTF("Too many pending packets\n");
1032#endif
1033            return 1;
1034        }
1035        dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
1036        ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
1037        usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, !flag_r,
1038                         OHCI_BM(td.flags, TD_DI) == 0);
1039        usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, pktlen);
1040        usb_handle_packet(dev, &ohci->usb_packet);
1041#ifdef DEBUG_PACKET
1042        DPRINTF("status=%d\n", ohci->usb_packet.status);
1043#endif
1044        if (ohci->usb_packet.status == USB_RET_ASYNC) {
1045            usb_device_flush_ep_queue(dev, ep);
1046            ohci->async_td = addr;
1047            return 1;
1048        }
1049    }
1050    if (ohci->usb_packet.status == USB_RET_SUCCESS) {
1051        ret = ohci->usb_packet.actual_length;
1052    } else {
1053        ret = ohci->usb_packet.status;
1054    }
1055
1056    if (ret >= 0) {
1057        if (dir == OHCI_TD_DIR_IN) {
1058            ohci_copy_td(ohci, &td, ohci->usb_buf, ret,
1059                         DMA_DIRECTION_FROM_DEVICE);
1060#ifdef DEBUG_PACKET
1061            DPRINTF("  data:");
1062            for (i = 0; i < ret; i++)
1063                printf(" %.2x", ohci->usb_buf[i]);
1064            DPRINTF("\n");
1065#endif
1066        } else {
1067            ret = pktlen;
1068        }
1069    }
1070
1071    /* Writeback */
1072    if (ret == pktlen || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {
1073        /* Transmission succeeded.  */
1074        if (ret == len) {
1075            td.cbp = 0;
1076        } else {
1077            if ((td.cbp & 0xfff) + ret > 0xfff) {
1078                td.cbp = (td.be & ~0xfff) + ((td.cbp + ret) & 0xfff);
1079            } else {
1080                td.cbp += ret;
1081            }
1082        }
1083        td.flags |= OHCI_TD_T1;
1084        td.flags ^= OHCI_TD_T0;
1085        OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);
1086        OHCI_SET_BM(td.flags, TD_EC, 0);
1087
1088        if ((dir != OHCI_TD_DIR_IN) && (ret != len)) {
1089            /* Partial packet transfer: TD not ready to retire yet */
1090            goto exit_no_retire;
1091        }
1092
1093        /* Setting ED_C is part of the TD retirement process */
1094        ed->head &= ~OHCI_ED_C;
1095        if (td.flags & OHCI_TD_T0)
1096            ed->head |= OHCI_ED_C;
1097    } else {
1098        if (ret >= 0) {
1099            DPRINTF("usb-ohci: Underrun\n");
1100            OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);
1101        } else {
1102            switch (ret) {
1103            case USB_RET_IOERROR:
1104            case USB_RET_NODEV:
1105                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);
1106            case USB_RET_NAK:
1107                DPRINTF("usb-ohci: got NAK\n");
1108                return 1;
1109            case USB_RET_STALL:
1110                DPRINTF("usb-ohci: got STALL\n");
1111                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);
1112                break;
1113            case USB_RET_BABBLE:
1114                DPRINTF("usb-ohci: got BABBLE\n");
1115                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
1116                break;
1117            default:
1118                fprintf(stderr, "usb-ohci: Bad device response %d\n", ret);
1119                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);
1120                OHCI_SET_BM(td.flags, TD_EC, 3);
1121                break;
1122            }
1123        }
1124        ed->head |= OHCI_ED_H;
1125    }
1126
1127    /* Retire this TD */
1128    ed->head &= ~OHCI_DPTR_MASK;
1129    ed->head |= td.next & OHCI_DPTR_MASK;
1130    td.next = ohci->done;
1131    ohci->done = addr;
1132    i = OHCI_BM(td.flags, TD_DI);
1133    if (i < ohci->done_count)
1134        ohci->done_count = i;
1135exit_no_retire:
1136    ohci_put_td(ohci, addr, &td);
1137    return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;
1138}
1139
1140/* Service an endpoint list.  Returns nonzero if active TD were found.  */
1141static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)
1142{
1143    struct ohci_ed ed;
1144    uint32_t next_ed;
1145    uint32_t cur;
1146    int active;
1147
1148    active = 0;
1149
1150    if (head == 0)
1151        return 0;
1152
1153    for (cur = head; cur; cur = next_ed) {
1154        if (!ohci_read_ed(ohci, cur, &ed)) {
1155            fprintf(stderr, "usb-ohci: ED read error at %x\n", cur);
1156            return 0;
1157        }
1158
1159        next_ed = ed.next & OHCI_DPTR_MASK;
1160
1161        if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {
1162            uint32_t addr;
1163            /* Cancel pending packets for ED that have been paused.  */
1164            addr = ed.head & OHCI_DPTR_MASK;
1165            if (ohci->async_td && addr == ohci->async_td) {
1166                usb_cancel_packet(&ohci->usb_packet);
1167                ohci->async_td = 0;
1168                usb_device_ep_stopped(ohci->usb_packet.ep->dev,
1169                                      ohci->usb_packet.ep);
1170            }
1171            continue;
1172        }
1173
1174        while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {
1175#ifdef DEBUG_PACKET
1176            DPRINTF("ED @ 0x%.8x fa=%u en=%u d=%u s=%u k=%u f=%u mps=%u "
1177                    "h=%u c=%u\n  head=0x%.8x tailp=0x%.8x next=0x%.8x\n", cur,
1178                    OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),
1179                    OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,
1180                    (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,
1181                    OHCI_BM(ed.flags, ED_MPS), (ed.head & OHCI_ED_H) != 0,
1182                    (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,
1183                    ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);
1184#endif
1185            active = 1;
1186
1187            if ((ed.flags & OHCI_ED_F) == 0) {
1188                if (ohci_service_td(ohci, &ed))
1189                    break;
1190            } else {
1191                /* Handle isochronous endpoints */
1192                if (ohci_service_iso_td(ohci, &ed, completion))
1193                    break;
1194            }
1195        }
1196
1197        ohci_put_ed(ohci, cur, &ed);
1198    }
1199
1200    return active;
1201}
1202
1203/* Generate a SOF event, and set a timer for EOF */
1204static void ohci_sof(OHCIState *ohci)
1205{
1206    ohci->sof_time = qemu_get_clock_ns(vm_clock);
1207    qemu_mod_timer(ohci->eof_timer, ohci->sof_time + usb_frame_time);
1208    ohci_set_interrupt(ohci, OHCI_INTR_SF);
1209}
1210
1211/* Process Control and Bulk lists.  */
1212static void ohci_process_lists(OHCIState *ohci, int completion)
1213{
1214    if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) {
1215        if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head) {
1216            DPRINTF("usb-ohci: head %x, cur %x\n",
1217                    ohci->ctrl_head, ohci->ctrl_cur);
1218        }
1219        if (!ohci_service_ed_list(ohci, ohci->ctrl_head, completion)) {
1220            ohci->ctrl_cur = 0;
1221            ohci->status &= ~OHCI_STATUS_CLF;
1222        }
1223    }
1224
1225    if ((ohci->ctl & OHCI_CTL_BLE) && (ohci->status & OHCI_STATUS_BLF)) {
1226        if (!ohci_service_ed_list(ohci, ohci->bulk_head, completion)) {
1227            ohci->bulk_cur = 0;
1228            ohci->status &= ~OHCI_STATUS_BLF;
1229        }
1230    }
1231}
1232
1233/* Do frame processing on frame boundary */
1234static void ohci_frame_boundary(void *opaque)
1235{
1236    OHCIState *ohci = opaque;
1237    struct ohci_hcca hcca;
1238
1239    ohci_read_hcca(ohci, ohci->hcca, &hcca);
1240
1241    /* Process all the lists at the end of the frame */
1242    if (ohci->ctl & OHCI_CTL_PLE) {
1243        int n;
1244
1245        n = ohci->frame_number & 0x1f;
1246        ohci_service_ed_list(ohci, le32_to_cpu(hcca.intr[n]), 0);
1247    }
1248
1249    /* Cancel all pending packets if either of the lists has been disabled.  */
1250    if (ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
1251        if (ohci->async_td) {
1252            usb_cancel_packet(&ohci->usb_packet);
1253            ohci->async_td = 0;
1254        }
1255        ohci_stop_endpoints(ohci);
1256    }
1257    ohci->old_ctl = ohci->ctl;
1258    ohci_process_lists(ohci, 0);
1259
1260    /* Frame boundary, so do EOF stuf here */
1261    ohci->frt = ohci->fit;
1262
1263    /* Increment frame number and take care of endianness. */
1264    ohci->frame_number = (ohci->frame_number + 1) & 0xffff;
1265    hcca.frame = cpu_to_le16(ohci->frame_number);
1266
1267    if (ohci->done_count == 0 && !(ohci->intr_status & OHCI_INTR_WD)) {
1268        if (!ohci->done)
1269            abort();
1270        if (ohci->intr & ohci->intr_status)
1271            ohci->done |= 1;
1272        hcca.done = cpu_to_le32(ohci->done);
1273        ohci->done = 0;
1274        ohci->done_count = 7;
1275        ohci_set_interrupt(ohci, OHCI_INTR_WD);
1276    }
1277
1278    if (ohci->done_count != 7 && ohci->done_count != 0)
1279        ohci->done_count--;
1280
1281    /* Do SOF stuff here */
1282    ohci_sof(ohci);
1283
1284    /* Writeback HCCA */
1285    ohci_put_hcca(ohci, ohci->hcca, &hcca);
1286}
1287
1288/* Start sending SOF tokens across the USB bus, lists are processed in
1289 * next frame
1290 */
1291static int ohci_bus_start(OHCIState *ohci)
1292{
1293    ohci->eof_timer = qemu_new_timer_ns(vm_clock,
1294                    ohci_frame_boundary,
1295                    ohci);
1296
1297    if (ohci->eof_timer == NULL) {
1298        fprintf(stderr, "usb-ohci: %s: qemu_new_timer_ns failed\n", ohci->name);
1299        /* TODO: Signal unrecoverable error */
1300        return 0;
1301    }
1302
1303    DPRINTF("usb-ohci: %s: USB Operational\n", ohci->name);
1304
1305    ohci_sof(ohci);
1306
1307    return 1;
1308}
1309
1310/* Stop sending SOF tokens on the bus */
1311static void ohci_bus_stop(OHCIState *ohci)
1312{
1313    if (ohci->eof_timer)
1314        qemu_del_timer(ohci->eof_timer);
1315    ohci->eof_timer = NULL;
1316}
1317
1318/* Sets a flag in a port status register but only set it if the port is
1319 * connected, if not set ConnectStatusChange flag. If flag is enabled
1320 * return 1.
1321 */
1322static int ohci_port_set_if_connected(OHCIState *ohci, int i, uint32_t val)
1323{
1324    int ret = 1;
1325
1326    /* writing a 0 has no effect */
1327    if (val == 0)
1328        return 0;
1329
1330    /* If CurrentConnectStatus is cleared we set
1331     * ConnectStatusChange
1332     */
1333    if (!(ohci->rhport[i].ctrl & OHCI_PORT_CCS)) {
1334        ohci->rhport[i].ctrl |= OHCI_PORT_CSC;
1335        if (ohci->rhstatus & OHCI_RHS_DRWE) {
1336            /* TODO: CSC is a wakeup event */
1337        }
1338        return 0;
1339    }
1340
1341    if (ohci->rhport[i].ctrl & val)
1342        ret = 0;
1343
1344    /* set the bit */
1345    ohci->rhport[i].ctrl |= val;
1346
1347    return ret;
1348}
1349
1350/* Set the frame interval - frame interval toggle is manipulated by the hcd only */
1351static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val)
1352{
1353    val &= OHCI_FMI_FI;
1354
1355    if (val != ohci->fi) {
1356        DPRINTF("usb-ohci: %s: FrameInterval = 0x%x (%u)\n",
1357            ohci->name, ohci->fi, ohci->fi);
1358    }
1359
1360    ohci->fi = val;
1361}
1362
1363static void ohci_port_power(OHCIState *ohci, int i, int p)
1364{
1365    if (p) {
1366        ohci->rhport[i].ctrl |= OHCI_PORT_PPS;
1367    } else {
1368        ohci->rhport[i].ctrl &= ~(OHCI_PORT_PPS|
1369                    OHCI_PORT_CCS|
1370                    OHCI_PORT_PSS|
1371                    OHCI_PORT_PRS);
1372    }
1373}
1374
1375/* Set HcControlRegister */
1376static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
1377{
1378    uint32_t old_state;
1379    uint32_t new_state;
1380
1381    old_state = ohci->ctl & OHCI_CTL_HCFS;
1382    ohci->ctl = val;
1383    new_state = ohci->ctl & OHCI_CTL_HCFS;
1384
1385    /* no state change */
1386    if (old_state == new_state)
1387        return;
1388
1389    switch (new_state) {
1390    case OHCI_USB_OPERATIONAL:
1391        ohci_bus_start(ohci);
1392        break;
1393    case OHCI_USB_SUSPEND:
1394        ohci_bus_stop(ohci);
1395        DPRINTF("usb-ohci: %s: USB Suspended\n", ohci->name);
1396        break;
1397    case OHCI_USB_RESUME:
1398        DPRINTF("usb-ohci: %s: USB Resume\n", ohci->name);
1399        break;
1400    case OHCI_USB_RESET:
1401        ohci_reset(ohci);
1402        DPRINTF("usb-ohci: %s: USB Reset\n", ohci->name);
1403        break;
1404    }
1405}
1406
1407static uint32_t ohci_get_frame_remaining(OHCIState *ohci)
1408{
1409    uint16_t fr;
1410    int64_t tks;
1411
1412    if ((ohci->ctl & OHCI_CTL_HCFS) != OHCI_USB_OPERATIONAL)
1413        return (ohci->frt << 31);
1414
1415    /* Being in USB operational state guarnatees sof_time was
1416     * set already.
1417     */
1418    tks = qemu_get_clock_ns(vm_clock) - ohci->sof_time;
1419
1420    /* avoid muldiv if possible */
1421    if (tks >= usb_frame_time)
1422        return (ohci->frt << 31);
1423
1424    tks = muldiv64(1, tks, usb_bit_time);
1425    fr = (uint16_t)(ohci->fi - tks);
1426
1427    return (ohci->frt << 31) | fr;
1428}
1429
1430
1431/* Set root hub status */
1432static void ohci_set_hub_status(OHCIState *ohci, uint32_t val)
1433{
1434    uint32_t old_state;
1435
1436    old_state = ohci->rhstatus;
1437
1438    /* write 1 to clear OCIC */
1439    if (val & OHCI_RHS_OCIC)
1440        ohci->rhstatus &= ~OHCI_RHS_OCIC;
1441
1442    if (val & OHCI_RHS_LPS) {
1443        int i;
1444
1445        for (i = 0; i < ohci->num_ports; i++)
1446            ohci_port_power(ohci, i, 0);
1447        DPRINTF("usb-ohci: powered down all ports\n");
1448    }
1449
1450    if (val & OHCI_RHS_LPSC) {
1451        int i;
1452
1453        for (i = 0; i < ohci->num_ports; i++)
1454            ohci_port_power(ohci, i, 1);
1455        DPRINTF("usb-ohci: powered up all ports\n");
1456    }
1457
1458    if (val & OHCI_RHS_DRWE)
1459        ohci->rhstatus |= OHCI_RHS_DRWE;
1460
1461    if (val & OHCI_RHS_CRWE)
1462        ohci->rhstatus &= ~OHCI_RHS_DRWE;
1463
1464    if (old_state != ohci->rhstatus)
1465        ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1466}
1467
1468/* Set root hub port status */
1469static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val)
1470{
1471    uint32_t old_state;
1472    OHCIPort *port;
1473
1474    port = &ohci->rhport[portnum];
1475    old_state = port->ctrl;
1476
1477    /* Write to clear CSC, PESC, PSSC, OCIC, PRSC */
1478    if (val & OHCI_PORT_WTC)
1479        port->ctrl &= ~(val & OHCI_PORT_WTC);
1480
1481    if (val & OHCI_PORT_CCS)
1482        port->ctrl &= ~OHCI_PORT_PES;
1483
1484    ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES);
1485
1486    if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS)) {
1487        DPRINTF("usb-ohci: port %d: SUSPEND\n", portnum);
1488    }
1489
1490    if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) {
1491        DPRINTF("usb-ohci: port %d: RESET\n", portnum);
1492        usb_device_reset(port->port.dev);
1493        port->ctrl &= ~OHCI_PORT_PRS;
1494        /* ??? Should this also set OHCI_PORT_PESC.  */
1495        port->ctrl |= OHCI_PORT_PES | OHCI_PORT_PRSC;
1496    }
1497
1498    /* Invert order here to ensure in ambiguous case, device is
1499     * powered up...
1500     */
1501    if (val & OHCI_PORT_LSDA)
1502        ohci_port_power(ohci, portnum, 0);
1503    if (val & OHCI_PORT_PPS)
1504        ohci_port_power(ohci, portnum, 1);
1505
1506    if (old_state != port->ctrl)
1507        ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1508}
1509
1510static uint64_t ohci_mem_read(void *opaque,
1511                              hwaddr addr,
1512                              unsigned size)
1513{
1514    OHCIState *ohci = opaque;
1515    uint32_t retval;
1516
1517    /* Only aligned reads are allowed on OHCI */
1518    if (addr & 3) {
1519        fprintf(stderr, "usb-ohci: Mis-aligned read\n");
1520        return 0xffffffff;
1521    } else if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1522        /* HcRhPortStatus */
1523        retval = ohci->rhport[(addr - 0x54) >> 2].ctrl | OHCI_PORT_PPS;
1524    } else {
1525        switch (addr >> 2) {
1526        case 0: /* HcRevision */
1527            retval = 0x10;
1528            break;
1529
1530        case 1: /* HcControl */
1531            retval = ohci->ctl;
1532            break;
1533
1534        case 2: /* HcCommandStatus */
1535            retval = ohci->status;
1536            break;
1537
1538        case 3: /* HcInterruptStatus */
1539            retval = ohci->intr_status;
1540            break;
1541
1542        case 4: /* HcInterruptEnable */
1543        case 5: /* HcInterruptDisable */
1544            retval = ohci->intr;
1545            break;
1546
1547        case 6: /* HcHCCA */
1548            retval = ohci->hcca;
1549            break;
1550
1551        case 7: /* HcPeriodCurrentED */
1552            retval = ohci->per_cur;
1553            break;
1554
1555        case 8: /* HcControlHeadED */
1556            retval = ohci->ctrl_head;
1557            break;
1558
1559        case 9: /* HcControlCurrentED */
1560            retval = ohci->ctrl_cur;
1561            break;
1562
1563        case 10: /* HcBulkHeadED */
1564            retval = ohci->bulk_head;
1565            break;
1566
1567        case 11: /* HcBulkCurrentED */
1568            retval = ohci->bulk_cur;
1569            break;
1570
1571        case 12: /* HcDoneHead */
1572            retval = ohci->done;
1573            break;
1574
1575        case 13: /* HcFmInterretval */
1576            retval = (ohci->fit << 31) | (ohci->fsmps << 16) | (ohci->fi);
1577            break;
1578
1579        case 14: /* HcFmRemaining */
1580            retval = ohci_get_frame_remaining(ohci);
1581            break;
1582
1583        case 15: /* HcFmNumber */
1584            retval = ohci->frame_number;
1585            break;
1586
1587        case 16: /* HcPeriodicStart */
1588            retval = ohci->pstart;
1589            break;
1590
1591        case 17: /* HcLSThreshold */
1592            retval = ohci->lst;
1593            break;
1594
1595        case 18: /* HcRhDescriptorA */
1596            retval = ohci->rhdesc_a;
1597            break;
1598
1599        case 19: /* HcRhDescriptorB */
1600            retval = ohci->rhdesc_b;
1601            break;
1602
1603        case 20: /* HcRhStatus */
1604            retval = ohci->rhstatus;
1605            break;
1606
1607        /* PXA27x specific registers */
1608        case 24: /* HcStatus */
1609            retval = ohci->hstatus & ohci->hmask;
1610            break;
1611
1612        case 25: /* HcHReset */
1613            retval = ohci->hreset;
1614            break;
1615
1616        case 26: /* HcHInterruptEnable */
1617            retval = ohci->hmask;
1618            break;
1619
1620        case 27: /* HcHInterruptTest */
1621            retval = ohci->htest;
1622            break;
1623
1624        default:
1625            fprintf(stderr, "ohci_read: Bad offset %x\n", (int)addr);
1626            retval = 0xffffffff;
1627        }
1628    }
1629
1630    return retval;
1631}
1632
1633static void ohci_mem_write(void *opaque,
1634                           hwaddr addr,
1635                           uint64_t val,
1636                           unsigned size)
1637{
1638    OHCIState *ohci = opaque;
1639
1640    /* Only aligned reads are allowed on OHCI */
1641    if (addr & 3) {
1642        fprintf(stderr, "usb-ohci: Mis-aligned write\n");
1643        return;
1644    }
1645
1646    if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1647        /* HcRhPortStatus */
1648        ohci_port_set_status(ohci, (addr - 0x54) >> 2, val);
1649        return;
1650    }
1651
1652    switch (addr >> 2) {
1653    case 1: /* HcControl */
1654        ohci_set_ctl(ohci, val);
1655        break;
1656
1657    case 2: /* HcCommandStatus */
1658        /* SOC is read-only */
1659        val = (val & ~OHCI_STATUS_SOC);
1660
1661        /* Bits written as '0' remain unchanged in the register */
1662        ohci->status |= val;
1663
1664        if (ohci->status & OHCI_STATUS_HCR)
1665            ohci_reset(ohci);
1666        break;
1667
1668    case 3: /* HcInterruptStatus */
1669        ohci->intr_status &= ~val;
1670        ohci_intr_update(ohci);
1671        break;
1672
1673    case 4: /* HcInterruptEnable */
1674        ohci->intr |= val;
1675        ohci_intr_update(ohci);
1676        break;
1677
1678    case 5: /* HcInterruptDisable */
1679        ohci->intr &= ~val;
1680        ohci_intr_update(ohci);
1681        break;
1682
1683    case 6: /* HcHCCA */
1684        ohci->hcca = val & OHCI_HCCA_MASK;
1685        break;
1686
1687    case 7: /* HcPeriodCurrentED */
1688        /* Ignore writes to this read-only register, Linux does them */
1689        break;
1690
1691    case 8: /* HcControlHeadED */
1692        ohci->ctrl_head = val & OHCI_EDPTR_MASK;
1693        break;
1694
1695    case 9: /* HcControlCurrentED */
1696        ohci->ctrl_cur = val & OHCI_EDPTR_MASK;
1697        break;
1698
1699    case 10: /* HcBulkHeadED */
1700        ohci->bulk_head = val & OHCI_EDPTR_MASK;
1701        break;
1702
1703    case 11: /* HcBulkCurrentED */
1704        ohci->bulk_cur = val & OHCI_EDPTR_MASK;
1705        break;
1706
1707    case 13: /* HcFmInterval */
1708        ohci->fsmps = (val & OHCI_FMI_FSMPS) >> 16;
1709        ohci->fit = (val & OHCI_FMI_FIT) >> 31;
1710        ohci_set_frame_interval(ohci, val);
1711        break;
1712
1713    case 15: /* HcFmNumber */
1714        break;
1715
1716    case 16: /* HcPeriodicStart */
1717        ohci->pstart = val & 0xffff;
1718        break;
1719
1720    case 17: /* HcLSThreshold */
1721        ohci->lst = val & 0xffff;
1722        break;
1723
1724    case 18: /* HcRhDescriptorA */
1725        ohci->rhdesc_a &= ~OHCI_RHA_RW_MASK;
1726        ohci->rhdesc_a |= val & OHCI_RHA_RW_MASK;
1727        break;
1728
1729    case 19: /* HcRhDescriptorB */
1730        break;
1731
1732    case 20: /* HcRhStatus */
1733        ohci_set_hub_status(ohci, val);
1734        break;
1735
1736    /* PXA27x specific registers */
1737    case 24: /* HcStatus */
1738        ohci->hstatus &= ~(val & ohci->hmask);
1739        break;
1740
1741    case 25: /* HcHReset */
1742        ohci->hreset = val & ~OHCI_HRESET_FSBIR;
1743        if (val & OHCI_HRESET_FSBIR)
1744            ohci_reset(ohci);
1745        break;
1746
1747    case 26: /* HcHInterruptEnable */
1748        ohci->hmask = val;
1749        break;
1750
1751    case 27: /* HcHInterruptTest */
1752        ohci->htest = val;
1753        break;
1754
1755    default:
1756        fprintf(stderr, "ohci_write: Bad offset %x\n", (int)addr);
1757        break;
1758    }
1759}
1760
1761static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev)
1762{
1763    if (ohci->async_td &&
1764        usb_packet_is_inflight(&ohci->usb_packet) &&
1765        ohci->usb_packet.ep->dev == dev) {
1766        usb_cancel_packet(&ohci->usb_packet);
1767        ohci->async_td = 0;
1768    }
1769}
1770
1771static const MemoryRegionOps ohci_mem_ops = {
1772    .read = ohci_mem_read,
1773    .write = ohci_mem_write,
1774    .endianness = DEVICE_LITTLE_ENDIAN,
1775};
1776
1777static USBPortOps ohci_port_ops = {
1778    .attach = ohci_attach,
1779    .detach = ohci_detach,
1780    .child_detach = ohci_child_detach,
1781    .wakeup = ohci_wakeup,
1782    .complete = ohci_async_complete_packet,
1783};
1784
1785static USBBusOps ohci_bus_ops = {
1786};
1787
1788static int usb_ohci_init(OHCIState *ohci, DeviceState *dev,
1789                         int num_ports, dma_addr_t localmem_base,
1790                         char *masterbus, uint32_t firstport,
1791                         DMAContext *dma)
1792{
1793    int i;
1794
1795    ohci->dma = dma;
1796
1797    if (usb_frame_time == 0) {
1798#ifdef OHCI_TIME_WARP
1799        usb_frame_time = get_ticks_per_sec();
1800        usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ/1000);
1801#else
1802        usb_frame_time = muldiv64(1, get_ticks_per_sec(), 1000);
1803        if (get_ticks_per_sec() >= USB_HZ) {
1804            usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ);
1805        } else {
1806            usb_bit_time = 1;
1807        }
1808#endif
1809        DPRINTF("usb-ohci: usb_bit_time=%" PRId64 " usb_frame_time=%" PRId64 "\n",
1810                usb_frame_time, usb_bit_time);
1811    }
1812
1813    ohci->num_ports = num_ports;
1814    if (masterbus) {
1815        USBPort *ports[OHCI_MAX_PORTS];
1816        for(i = 0; i < num_ports; i++) {
1817            ports[i] = &ohci->rhport[i].port;
1818        }
1819        if (usb_register_companion(masterbus, ports, num_ports,
1820                firstport, ohci, &ohci_port_ops,
1821                USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL) != 0) {
1822            return -1;
1823        }
1824    } else {
1825        usb_bus_new(&ohci->bus, &ohci_bus_ops, dev);
1826        for (i = 0; i < num_ports; i++) {
1827            usb_register_port(&ohci->bus, &ohci->rhport[i].port,
1828                              ohci, i, &ohci_port_ops,
1829                              USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1830        }
1831    }
1832
1833    memory_region_init_io(&ohci->mem, &ohci_mem_ops, ohci, "ohci", 256);
1834    ohci->localmem_base = localmem_base;
1835
1836    ohci->name = object_get_typename(OBJECT(dev));
1837    usb_packet_init(&ohci->usb_packet);
1838
1839    ohci->async_td = 0;
1840    qemu_register_reset(ohci_reset, ohci);
1841
1842    return 0;
1843}
1844
1845typedef struct {
1846    PCIDevice pci_dev;
1847    OHCIState state;
1848    char *masterbus;
1849    uint32_t num_ports;
1850    uint32_t firstport;
1851} OHCIPCIState;
1852
1853static int usb_ohci_initfn_pci(struct PCIDevice *dev)
1854{
1855    OHCIPCIState *ohci = DO_UPCAST(OHCIPCIState, pci_dev, dev);
1856
1857    ohci->pci_dev.config[PCI_CLASS_PROG] = 0x10; /* OHCI */
1858    ohci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1859
1860    if (usb_ohci_init(&ohci->state, &dev->qdev, ohci->num_ports, 0,
1861                      ohci->masterbus, ohci->firstport,
1862                      pci_dma_context(dev)) != 0) {
1863        return -1;
1864    }
1865    ohci->state.irq = ohci->pci_dev.irq[0];
1866
1867    /* TODO: avoid cast below by using dev */
1868    pci_register_bar(&ohci->pci_dev, 0, 0, &ohci->state.mem);
1869    return 0;
1870}
1871
1872typedef struct {
1873    SysBusDevice busdev;
1874    OHCIState ohci;
1875    uint32_t num_ports;
1876    dma_addr_t dma_offset;
1877} OHCISysBusState;
1878
1879static int ohci_init_pxa(SysBusDevice *dev)
1880{
1881    OHCISysBusState *s = FROM_SYSBUS(OHCISysBusState, dev);
1882
1883    /* Cannot fail as we pass NULL for masterbus */
1884    usb_ohci_init(&s->ohci, &dev->qdev, s->num_ports, s->dma_offset, NULL, 0,
1885                  &dma_context_memory);
1886    sysbus_init_irq(dev, &s->ohci.irq);
1887    sysbus_init_mmio(dev, &s->ohci.mem);
1888
1889    return 0;
1890}
1891
1892static Property ohci_pci_properties[] = {
1893    DEFINE_PROP_STRING("masterbus", OHCIPCIState, masterbus),
1894    DEFINE_PROP_UINT32("num-ports", OHCIPCIState, num_ports, 3),
1895    DEFINE_PROP_UINT32("firstport", OHCIPCIState, firstport, 0),
1896    DEFINE_PROP_END_OF_LIST(),
1897};
1898
1899static void ohci_pci_class_init(ObjectClass *klass, void *data)
1900{
1901    DeviceClass *dc = DEVICE_CLASS(klass);
1902    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1903
1904    k->init = usb_ohci_initfn_pci;
1905    k->vendor_id = PCI_VENDOR_ID_APPLE;
1906    k->device_id = PCI_DEVICE_ID_APPLE_IPID_USB;
1907    k->class_id = PCI_CLASS_SERIAL_USB;
1908    k->no_hotplug = 1;
1909    dc->desc = "Apple USB Controller";
1910    dc->props = ohci_pci_properties;
1911}
1912
1913static const TypeInfo ohci_pci_info = {
1914    .name          = "pci-ohci",
1915    .parent        = TYPE_PCI_DEVICE,
1916    .instance_size = sizeof(OHCIPCIState),
1917    .class_init    = ohci_pci_class_init,
1918};
1919
1920static Property ohci_sysbus_properties[] = {
1921    DEFINE_PROP_UINT32("num-ports", OHCISysBusState, num_ports, 3),
1922    DEFINE_PROP_DMAADDR("dma-offset", OHCISysBusState, dma_offset, 3),
1923    DEFINE_PROP_END_OF_LIST(),
1924};
1925
1926static void ohci_sysbus_class_init(ObjectClass *klass, void *data)
1927{
1928    DeviceClass *dc = DEVICE_CLASS(klass);
1929    SysBusDeviceClass *sbc = SYS_BUS_DEVICE_CLASS(klass);
1930
1931    sbc->init = ohci_init_pxa;
1932    dc->desc = "OHCI USB Controller";
1933    dc->props = ohci_sysbus_properties;
1934}
1935
1936static const TypeInfo ohci_sysbus_info = {
1937    .name          = "sysbus-ohci",
1938    .parent        = TYPE_SYS_BUS_DEVICE,
1939    .instance_size = sizeof(OHCISysBusState),
1940    .class_init    = ohci_sysbus_class_init,
1941};
1942
1943static void ohci_register_types(void)
1944{
1945    type_register_static(&ohci_pci_info);
1946    type_register_static(&ohci_sysbus_info);
1947}
1948
1949type_init(ohci_register_types)
1950