qemu/hw/ide/ahci.c
<<
>>
Prefs
   1/*
   2 * QEMU AHCI Emulation
   3 *
   4 * Copyright (c) 2010 qiaochong@loongson.cn
   5 * Copyright (c) 2010 Roland Elek <elek.roland@gmail.com>
   6 * Copyright (c) 2010 Sebastian Herbszt <herbszt@gmx.de>
   7 * Copyright (c) 2010 Alexander Graf <agraf@suse.de>
   8 *
   9 * This library is free software; you can redistribute it and/or
  10 * modify it under the terms of the GNU Lesser General Public
  11 * License as published by the Free Software Foundation; either
  12 * version 2 of the License, or (at your option) any later version.
  13 *
  14 * This library is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17 * Lesser General Public License for more details.
  18 *
  19 * You should have received a copy of the GNU Lesser General Public
  20 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  21 *
  22 */
  23
  24#include "qemu/osdep.h"
  25#include <hw/hw.h>
  26#include <hw/pci/msi.h>
  27#include <hw/i386/pc.h>
  28#include <hw/pci/pci.h>
  29
  30#include "qemu/error-report.h"
  31#include "sysemu/block-backend.h"
  32#include "sysemu/dma.h"
  33#include "internal.h"
  34#include <hw/ide/pci.h>
  35#include <hw/ide/ahci.h>
  36
  37#define DEBUG_AHCI 0
  38
  39#define DPRINTF(port, fmt, ...) \
  40do { \
  41    if (DEBUG_AHCI) { \
  42        fprintf(stderr, "ahci: %s: [%d] ", __func__, port); \
  43        fprintf(stderr, fmt, ## __VA_ARGS__); \
  44    } \
  45} while (0)
  46
  47static void check_cmd(AHCIState *s, int port);
  48static int handle_cmd(AHCIState *s, int port, uint8_t slot);
  49static void ahci_reset_port(AHCIState *s, int port);
  50static bool ahci_write_fis_d2h(AHCIDevice *ad);
  51static void ahci_init_d2h(AHCIDevice *ad);
  52static int ahci_dma_prepare_buf(IDEDMA *dma, int32_t limit);
  53static bool ahci_map_clb_address(AHCIDevice *ad);
  54static bool ahci_map_fis_address(AHCIDevice *ad);
  55static void ahci_unmap_clb_address(AHCIDevice *ad);
  56static void ahci_unmap_fis_address(AHCIDevice *ad);
  57
  58
  59static uint32_t  ahci_port_read(AHCIState *s, int port, int offset)
  60{
  61    uint32_t val;
  62    AHCIPortRegs *pr;
  63    pr = &s->dev[port].port_regs;
  64
  65    switch (offset) {
  66    case PORT_LST_ADDR:
  67        val = pr->lst_addr;
  68        break;
  69    case PORT_LST_ADDR_HI:
  70        val = pr->lst_addr_hi;
  71        break;
  72    case PORT_FIS_ADDR:
  73        val = pr->fis_addr;
  74        break;
  75    case PORT_FIS_ADDR_HI:
  76        val = pr->fis_addr_hi;
  77        break;
  78    case PORT_IRQ_STAT:
  79        val = pr->irq_stat;
  80        break;
  81    case PORT_IRQ_MASK:
  82        val = pr->irq_mask;
  83        break;
  84    case PORT_CMD:
  85        val = pr->cmd;
  86        break;
  87    case PORT_TFDATA:
  88        val = pr->tfdata;
  89        break;
  90    case PORT_SIG:
  91        val = pr->sig;
  92        break;
  93    case PORT_SCR_STAT:
  94        if (s->dev[port].port.ifs[0].blk) {
  95            val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP |
  96                  SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE;
  97        } else {
  98            val = SATA_SCR_SSTATUS_DET_NODEV;
  99        }
 100        break;
 101    case PORT_SCR_CTL:
 102        val = pr->scr_ctl;
 103        break;
 104    case PORT_SCR_ERR:
 105        val = pr->scr_err;
 106        break;
 107    case PORT_SCR_ACT:
 108        val = pr->scr_act;
 109        break;
 110    case PORT_CMD_ISSUE:
 111        val = pr->cmd_issue;
 112        break;
 113    case PORT_RESERVED:
 114    default:
 115        val = 0;
 116    }
 117    DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
 118    return val;
 119
 120}
 121
 122static void ahci_irq_raise(AHCIState *s, AHCIDevice *dev)
 123{
 124    DeviceState *dev_state = s->container;
 125    PCIDevice *pci_dev = (PCIDevice *) object_dynamic_cast(OBJECT(dev_state),
 126                                                           TYPE_PCI_DEVICE);
 127
 128    DPRINTF(0, "raise irq\n");
 129
 130    if (pci_dev && msi_enabled(pci_dev)) {
 131        msi_notify(pci_dev, 0);
 132    } else {
 133        qemu_irq_raise(s->irq);
 134    }
 135}
 136
 137static void ahci_irq_lower(AHCIState *s, AHCIDevice *dev)
 138{
 139    DeviceState *dev_state = s->container;
 140    PCIDevice *pci_dev = (PCIDevice *) object_dynamic_cast(OBJECT(dev_state),
 141                                                           TYPE_PCI_DEVICE);
 142
 143    DPRINTF(0, "lower irq\n");
 144
 145    if (!pci_dev || !msi_enabled(pci_dev)) {
 146        qemu_irq_lower(s->irq);
 147    }
 148}
 149
 150static void ahci_check_irq(AHCIState *s)
 151{
 152    int i;
 153
 154    DPRINTF(-1, "check irq %#x\n", s->control_regs.irqstatus);
 155
 156    s->control_regs.irqstatus = 0;
 157    for (i = 0; i < s->ports; i++) {
 158        AHCIPortRegs *pr = &s->dev[i].port_regs;
 159        if (pr->irq_stat & pr->irq_mask) {
 160            s->control_regs.irqstatus |= (1 << i);
 161        }
 162    }
 163
 164    if (s->control_regs.irqstatus &&
 165        (s->control_regs.ghc & HOST_CTL_IRQ_EN)) {
 166            ahci_irq_raise(s, NULL);
 167    } else {
 168        ahci_irq_lower(s, NULL);
 169    }
 170}
 171
 172static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d,
 173                             int irq_type)
 174{
 175    DPRINTF(d->port_no, "trigger irq %#x -> %x\n",
 176            irq_type, d->port_regs.irq_mask & irq_type);
 177
 178    d->port_regs.irq_stat |= irq_type;
 179    ahci_check_irq(s);
 180}
 181
 182static void map_page(AddressSpace *as, uint8_t **ptr, uint64_t addr,
 183                     uint32_t wanted)
 184{
 185    hwaddr len = wanted;
 186
 187    if (*ptr) {
 188        dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
 189    }
 190
 191    *ptr = dma_memory_map(as, addr, &len, DMA_DIRECTION_FROM_DEVICE);
 192    if (len < wanted) {
 193        dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
 194        *ptr = NULL;
 195    }
 196}
 197
 198/**
 199 * Check the cmd register to see if we should start or stop
 200 * the DMA or FIS RX engines.
 201 *
 202 * @ad: Device to dis/engage.
 203 *
 204 * @return 0 on success, -1 on error.
 205 */
 206static int ahci_cond_start_engines(AHCIDevice *ad)
 207{
 208    AHCIPortRegs *pr = &ad->port_regs;
 209    bool cmd_start = pr->cmd & PORT_CMD_START;
 210    bool cmd_on    = pr->cmd & PORT_CMD_LIST_ON;
 211    bool fis_start = pr->cmd & PORT_CMD_FIS_RX;
 212    bool fis_on    = pr->cmd & PORT_CMD_FIS_ON;
 213
 214    if (cmd_start && !cmd_on) {
 215        if (!ahci_map_clb_address(ad)) {
 216            pr->cmd &= ~PORT_CMD_START;
 217            error_report("AHCI: Failed to start DMA engine: "
 218                         "bad command list buffer address");
 219            return -1;
 220        }
 221    } else if (!cmd_start && cmd_on) {
 222        ahci_unmap_clb_address(ad);
 223    }
 224
 225    if (fis_start && !fis_on) {
 226        if (!ahci_map_fis_address(ad)) {
 227            pr->cmd &= ~PORT_CMD_FIS_RX;
 228            error_report("AHCI: Failed to start FIS receive engine: "
 229                         "bad FIS receive buffer address");
 230            return -1;
 231        }
 232    } else if (!fis_start && fis_on) {
 233        ahci_unmap_fis_address(ad);
 234    }
 235
 236    return 0;
 237}
 238
 239static void  ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)
 240{
 241    AHCIPortRegs *pr = &s->dev[port].port_regs;
 242
 243    DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
 244    switch (offset) {
 245        case PORT_LST_ADDR:
 246            pr->lst_addr = val;
 247            break;
 248        case PORT_LST_ADDR_HI:
 249            pr->lst_addr_hi = val;
 250            break;
 251        case PORT_FIS_ADDR:
 252            pr->fis_addr = val;
 253            break;
 254        case PORT_FIS_ADDR_HI:
 255            pr->fis_addr_hi = val;
 256            break;
 257        case PORT_IRQ_STAT:
 258            pr->irq_stat &= ~val;
 259            ahci_check_irq(s);
 260            break;
 261        case PORT_IRQ_MASK:
 262            pr->irq_mask = val & 0xfdc000ff;
 263            ahci_check_irq(s);
 264            break;
 265        case PORT_CMD:
 266            /* Block any Read-only fields from being set;
 267             * including LIST_ON and FIS_ON.
 268             * The spec requires to set ICC bits to zero after the ICC change
 269             * is done. We don't support ICC state changes, therefore always
 270             * force the ICC bits to zero.
 271             */
 272            pr->cmd = (pr->cmd & PORT_CMD_RO_MASK) |
 273                      (val & ~(PORT_CMD_RO_MASK|PORT_CMD_ICC_MASK));
 274
 275            /* Check FIS RX and CLB engines */
 276            ahci_cond_start_engines(&s->dev[port]);
 277
 278            /* XXX usually the FIS would be pending on the bus here and
 279                   issuing deferred until the OS enables FIS receival.
 280                   Instead, we only submit it once - which works in most
 281                   cases, but is a hack. */
 282            if ((pr->cmd & PORT_CMD_FIS_ON) &&
 283                !s->dev[port].init_d2h_sent) {
 284                ahci_init_d2h(&s->dev[port]);
 285            }
 286
 287            check_cmd(s, port);
 288            break;
 289        case PORT_TFDATA:
 290            /* Read Only. */
 291            break;
 292        case PORT_SIG:
 293            /* Read Only */
 294            break;
 295        case PORT_SCR_STAT:
 296            /* Read Only */
 297            break;
 298        case PORT_SCR_CTL:
 299            if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&
 300                ((val & AHCI_SCR_SCTL_DET) == 0)) {
 301                ahci_reset_port(s, port);
 302            }
 303            pr->scr_ctl = val;
 304            break;
 305        case PORT_SCR_ERR:
 306            pr->scr_err &= ~val;
 307            break;
 308        case PORT_SCR_ACT:
 309            /* RW1 */
 310            pr->scr_act |= val;
 311            break;
 312        case PORT_CMD_ISSUE:
 313            pr->cmd_issue |= val;
 314            check_cmd(s, port);
 315            break;
 316        default:
 317            break;
 318    }
 319}
 320
 321static uint64_t ahci_mem_read_32(void *opaque, hwaddr addr)
 322{
 323    AHCIState *s = opaque;
 324    uint32_t val = 0;
 325
 326    if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
 327        switch (addr) {
 328        case HOST_CAP:
 329            val = s->control_regs.cap;
 330            break;
 331        case HOST_CTL:
 332            val = s->control_regs.ghc;
 333            break;
 334        case HOST_IRQ_STAT:
 335            val = s->control_regs.irqstatus;
 336            break;
 337        case HOST_PORTS_IMPL:
 338            val = s->control_regs.impl;
 339            break;
 340        case HOST_VERSION:
 341            val = s->control_regs.version;
 342            break;
 343        }
 344
 345        DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val);
 346    } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
 347               (addr < (AHCI_PORT_REGS_START_ADDR +
 348                (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
 349        val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
 350                             addr & AHCI_PORT_ADDR_OFFSET_MASK);
 351    }
 352
 353    return val;
 354}
 355
 356
 357/**
 358 * AHCI 1.3 section 3 ("HBA Memory Registers")
 359 * Support unaligned 8/16/32 bit reads, and 64 bit aligned reads.
 360 * Caller is responsible for masking unwanted higher order bytes.
 361 */
 362static uint64_t ahci_mem_read(void *opaque, hwaddr addr, unsigned size)
 363{
 364    hwaddr aligned = addr & ~0x3;
 365    int ofst = addr - aligned;
 366    uint64_t lo = ahci_mem_read_32(opaque, aligned);
 367    uint64_t hi;
 368    uint64_t val;
 369
 370    /* if < 8 byte read does not cross 4 byte boundary */
 371    if (ofst + size <= 4) {
 372        val = lo >> (ofst * 8);
 373    } else {
 374        g_assert_cmpint(size, >, 1);
 375
 376        /* If the 64bit read is unaligned, we will produce undefined
 377         * results. AHCI does not support unaligned 64bit reads. */
 378        hi = ahci_mem_read_32(opaque, aligned + 4);
 379        val = (hi << 32 | lo) >> (ofst * 8);
 380    }
 381
 382    DPRINTF(-1, "addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 ", size=%d\n",
 383            addr, val, size);
 384    return val;
 385}
 386
 387
 388static void ahci_mem_write(void *opaque, hwaddr addr,
 389                           uint64_t val, unsigned size)
 390{
 391    AHCIState *s = opaque;
 392
 393    DPRINTF(-1, "addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 ", size=%d\n",
 394            addr, val, size);
 395
 396    /* Only aligned reads are allowed on AHCI */
 397    if (addr & 3) {
 398        fprintf(stderr, "ahci: Mis-aligned write to addr 0x"
 399                TARGET_FMT_plx "\n", addr);
 400        return;
 401    }
 402
 403    if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
 404        DPRINTF(-1, "(addr 0x%08X), val 0x%08"PRIX64"\n", (unsigned) addr, val);
 405
 406        switch (addr) {
 407            case HOST_CAP: /* R/WO, RO */
 408                /* FIXME handle R/WO */
 409                break;
 410            case HOST_CTL: /* R/W */
 411                if (val & HOST_CTL_RESET) {
 412                    DPRINTF(-1, "HBA Reset\n");
 413                    ahci_reset(s);
 414                } else {
 415                    s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;
 416                    ahci_check_irq(s);
 417                }
 418                break;
 419            case HOST_IRQ_STAT: /* R/WC, RO */
 420                s->control_regs.irqstatus &= ~val;
 421                ahci_check_irq(s);
 422                break;
 423            case HOST_PORTS_IMPL: /* R/WO, RO */
 424                /* FIXME handle R/WO */
 425                break;
 426            case HOST_VERSION: /* RO */
 427                /* FIXME report write? */
 428                break;
 429            default:
 430                DPRINTF(-1, "write to unknown register 0x%x\n", (unsigned)addr);
 431        }
 432    } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
 433               (addr < (AHCI_PORT_REGS_START_ADDR +
 434                (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
 435        ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
 436                        addr & AHCI_PORT_ADDR_OFFSET_MASK, val);
 437    }
 438
 439}
 440
 441static const MemoryRegionOps ahci_mem_ops = {
 442    .read = ahci_mem_read,
 443    .write = ahci_mem_write,
 444    .endianness = DEVICE_LITTLE_ENDIAN,
 445};
 446
 447static uint64_t ahci_idp_read(void *opaque, hwaddr addr,
 448                              unsigned size)
 449{
 450    AHCIState *s = opaque;
 451
 452    if (addr == s->idp_offset) {
 453        /* index register */
 454        return s->idp_index;
 455    } else if (addr == s->idp_offset + 4) {
 456        /* data register - do memory read at location selected by index */
 457        return ahci_mem_read(opaque, s->idp_index, size);
 458    } else {
 459        return 0;
 460    }
 461}
 462
 463static void ahci_idp_write(void *opaque, hwaddr addr,
 464                           uint64_t val, unsigned size)
 465{
 466    AHCIState *s = opaque;
 467
 468    if (addr == s->idp_offset) {
 469        /* index register - mask off reserved bits */
 470        s->idp_index = (uint32_t)val & ((AHCI_MEM_BAR_SIZE - 1) & ~3);
 471    } else if (addr == s->idp_offset + 4) {
 472        /* data register - do memory write at location selected by index */
 473        ahci_mem_write(opaque, s->idp_index, val, size);
 474    }
 475}
 476
 477static const MemoryRegionOps ahci_idp_ops = {
 478    .read = ahci_idp_read,
 479    .write = ahci_idp_write,
 480    .endianness = DEVICE_LITTLE_ENDIAN,
 481};
 482
 483
 484static void ahci_reg_init(AHCIState *s)
 485{
 486    int i;
 487
 488    s->control_regs.cap = (s->ports - 1) |
 489                          (AHCI_NUM_COMMAND_SLOTS << 8) |
 490                          (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) |
 491                          HOST_CAP_NCQ | HOST_CAP_AHCI;
 492
 493    s->control_regs.impl = (1 << s->ports) - 1;
 494
 495    s->control_regs.version = AHCI_VERSION_1_0;
 496
 497    for (i = 0; i < s->ports; i++) {
 498        s->dev[i].port_state = STATE_RUN;
 499    }
 500}
 501
 502static void check_cmd(AHCIState *s, int port)
 503{
 504    AHCIPortRegs *pr = &s->dev[port].port_regs;
 505    uint8_t slot;
 506
 507    if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) {
 508        for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) {
 509            if ((pr->cmd_issue & (1U << slot)) &&
 510                !handle_cmd(s, port, slot)) {
 511                pr->cmd_issue &= ~(1U << slot);
 512            }
 513        }
 514    }
 515}
 516
 517static void ahci_check_cmd_bh(void *opaque)
 518{
 519    AHCIDevice *ad = opaque;
 520
 521    qemu_bh_delete(ad->check_bh);
 522    ad->check_bh = NULL;
 523
 524    if ((ad->busy_slot != -1) &&
 525        !(ad->port.ifs[0].status & (BUSY_STAT|DRQ_STAT))) {
 526        /* no longer busy */
 527        ad->port_regs.cmd_issue &= ~(1 << ad->busy_slot);
 528        ad->busy_slot = -1;
 529    }
 530
 531    check_cmd(ad->hba, ad->port_no);
 532}
 533
 534static void ahci_init_d2h(AHCIDevice *ad)
 535{
 536    IDEState *ide_state = &ad->port.ifs[0];
 537    AHCIPortRegs *pr = &ad->port_regs;
 538
 539    if (ad->init_d2h_sent) {
 540        return;
 541    }
 542
 543    if (ahci_write_fis_d2h(ad)) {
 544        ad->init_d2h_sent = true;
 545        /* We're emulating receiving the first Reg H2D Fis from the device;
 546         * Update the SIG register, but otherwise proceed as normal. */
 547        pr->sig = ((uint32_t)ide_state->hcyl << 24) |
 548            (ide_state->lcyl << 16) |
 549            (ide_state->sector << 8) |
 550            (ide_state->nsector & 0xFF);
 551    }
 552}
 553
 554static void ahci_set_signature(AHCIDevice *ad, uint32_t sig)
 555{
 556    IDEState *s = &ad->port.ifs[0];
 557    s->hcyl = sig >> 24 & 0xFF;
 558    s->lcyl = sig >> 16 & 0xFF;
 559    s->sector = sig >> 8 & 0xFF;
 560    s->nsector = sig & 0xFF;
 561
 562    DPRINTF(ad->port_no, "set hcyl:lcyl:sect:nsect = 0x%08x\n", sig);
 563}
 564
 565static void ahci_reset_port(AHCIState *s, int port)
 566{
 567    AHCIDevice *d = &s->dev[port];
 568    AHCIPortRegs *pr = &d->port_regs;
 569    IDEState *ide_state = &d->port.ifs[0];
 570    int i;
 571
 572    DPRINTF(port, "reset port\n");
 573
 574    ide_bus_reset(&d->port);
 575    ide_state->ncq_queues = AHCI_MAX_CMDS;
 576
 577    pr->scr_stat = 0;
 578    pr->scr_err = 0;
 579    pr->scr_act = 0;
 580    pr->tfdata = 0x7F;
 581    pr->sig = 0xFFFFFFFF;
 582    d->busy_slot = -1;
 583    d->init_d2h_sent = false;
 584
 585    ide_state = &s->dev[port].port.ifs[0];
 586    if (!ide_state->blk) {
 587        return;
 588    }
 589
 590    /* reset ncq queue */
 591    for (i = 0; i < AHCI_MAX_CMDS; i++) {
 592        NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[i];
 593        ncq_tfs->halt = false;
 594        if (!ncq_tfs->used) {
 595            continue;
 596        }
 597
 598        if (ncq_tfs->aiocb) {
 599            blk_aio_cancel(ncq_tfs->aiocb);
 600            ncq_tfs->aiocb = NULL;
 601        }
 602
 603        /* Maybe we just finished the request thanks to blk_aio_cancel() */
 604        if (!ncq_tfs->used) {
 605            continue;
 606        }
 607
 608        qemu_sglist_destroy(&ncq_tfs->sglist);
 609        ncq_tfs->used = 0;
 610    }
 611
 612    s->dev[port].port_state = STATE_RUN;
 613    if (ide_state->drive_kind == IDE_CD) {
 614        ahci_set_signature(d, SATA_SIGNATURE_CDROM);\
 615        ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT;
 616    } else {
 617        ahci_set_signature(d, SATA_SIGNATURE_DISK);
 618        ide_state->status = SEEK_STAT | WRERR_STAT;
 619    }
 620
 621    ide_state->error = 1;
 622    ahci_init_d2h(d);
 623}
 624
 625static void debug_print_fis(uint8_t *fis, int cmd_len)
 626{
 627#if DEBUG_AHCI
 628    int i;
 629
 630    fprintf(stderr, "fis:");
 631    for (i = 0; i < cmd_len; i++) {
 632        if ((i & 0xf) == 0) {
 633            fprintf(stderr, "\n%02x:",i);
 634        }
 635        fprintf(stderr, "%02x ",fis[i]);
 636    }
 637    fprintf(stderr, "\n");
 638#endif
 639}
 640
 641static bool ahci_map_fis_address(AHCIDevice *ad)
 642{
 643    AHCIPortRegs *pr = &ad->port_regs;
 644    map_page(ad->hba->as, &ad->res_fis,
 645             ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
 646    if (ad->res_fis != NULL) {
 647        pr->cmd |= PORT_CMD_FIS_ON;
 648        return true;
 649    }
 650
 651    pr->cmd &= ~PORT_CMD_FIS_ON;
 652    return false;
 653}
 654
 655static void ahci_unmap_fis_address(AHCIDevice *ad)
 656{
 657    if (ad->res_fis == NULL) {
 658        DPRINTF(ad->port_no, "Attempt to unmap NULL FIS address\n");
 659        return;
 660    }
 661    ad->port_regs.cmd &= ~PORT_CMD_FIS_ON;
 662    dma_memory_unmap(ad->hba->as, ad->res_fis, 256,
 663                     DMA_DIRECTION_FROM_DEVICE, 256);
 664    ad->res_fis = NULL;
 665}
 666
 667static bool ahci_map_clb_address(AHCIDevice *ad)
 668{
 669    AHCIPortRegs *pr = &ad->port_regs;
 670    ad->cur_cmd = NULL;
 671    map_page(ad->hba->as, &ad->lst,
 672             ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
 673    if (ad->lst != NULL) {
 674        pr->cmd |= PORT_CMD_LIST_ON;
 675        return true;
 676    }
 677
 678    pr->cmd &= ~PORT_CMD_LIST_ON;
 679    return false;
 680}
 681
 682static void ahci_unmap_clb_address(AHCIDevice *ad)
 683{
 684    if (ad->lst == NULL) {
 685        DPRINTF(ad->port_no, "Attempt to unmap NULL CLB address\n");
 686        return;
 687    }
 688    ad->port_regs.cmd &= ~PORT_CMD_LIST_ON;
 689    dma_memory_unmap(ad->hba->as, ad->lst, 1024,
 690                     DMA_DIRECTION_FROM_DEVICE, 1024);
 691    ad->lst = NULL;
 692}
 693
 694static void ahci_write_fis_sdb(AHCIState *s, NCQTransferState *ncq_tfs)
 695{
 696    AHCIDevice *ad = ncq_tfs->drive;
 697    AHCIPortRegs *pr = &ad->port_regs;
 698    IDEState *ide_state;
 699    SDBFIS *sdb_fis;
 700
 701    if (!ad->res_fis ||
 702        !(pr->cmd & PORT_CMD_FIS_RX)) {
 703        return;
 704    }
 705
 706    sdb_fis = (SDBFIS *)&ad->res_fis[RES_FIS_SDBFIS];
 707    ide_state = &ad->port.ifs[0];
 708
 709    sdb_fis->type = SATA_FIS_TYPE_SDB;
 710    /* Interrupt pending & Notification bit */
 711    sdb_fis->flags = 0x40; /* Interrupt bit, always 1 for NCQ */
 712    sdb_fis->status = ide_state->status & 0x77;
 713    sdb_fis->error = ide_state->error;
 714    /* update SAct field in SDB_FIS */
 715    sdb_fis->payload = cpu_to_le32(ad->finished);
 716
 717    /* Update shadow registers (except BSY 0x80 and DRQ 0x08) */
 718    pr->tfdata = (ad->port.ifs[0].error << 8) |
 719        (ad->port.ifs[0].status & 0x77) |
 720        (pr->tfdata & 0x88);
 721    pr->scr_act &= ~ad->finished;
 722    ad->finished = 0;
 723
 724    /* Trigger IRQ if interrupt bit is set (which currently, it always is) */
 725    if (sdb_fis->flags & 0x40) {
 726        ahci_trigger_irq(s, ad, PORT_IRQ_SDB_FIS);
 727    }
 728}
 729
 730static void ahci_write_fis_pio(AHCIDevice *ad, uint16_t len)
 731{
 732    AHCIPortRegs *pr = &ad->port_regs;
 733    uint8_t *pio_fis;
 734    IDEState *s = &ad->port.ifs[0];
 735
 736    if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
 737        return;
 738    }
 739
 740    pio_fis = &ad->res_fis[RES_FIS_PSFIS];
 741
 742    pio_fis[0] = SATA_FIS_TYPE_PIO_SETUP;
 743    pio_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
 744    pio_fis[2] = s->status;
 745    pio_fis[3] = s->error;
 746
 747    pio_fis[4] = s->sector;
 748    pio_fis[5] = s->lcyl;
 749    pio_fis[6] = s->hcyl;
 750    pio_fis[7] = s->select;
 751    pio_fis[8] = s->hob_sector;
 752    pio_fis[9] = s->hob_lcyl;
 753    pio_fis[10] = s->hob_hcyl;
 754    pio_fis[11] = 0;
 755    pio_fis[12] = s->nsector & 0xFF;
 756    pio_fis[13] = (s->nsector >> 8) & 0xFF;
 757    pio_fis[14] = 0;
 758    pio_fis[15] = s->status;
 759    pio_fis[16] = len & 255;
 760    pio_fis[17] = len >> 8;
 761    pio_fis[18] = 0;
 762    pio_fis[19] = 0;
 763
 764    /* Update shadow registers: */
 765    pr->tfdata = (ad->port.ifs[0].error << 8) |
 766        ad->port.ifs[0].status;
 767
 768    if (pio_fis[2] & ERR_STAT) {
 769        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
 770    }
 771
 772    ahci_trigger_irq(ad->hba, ad, PORT_IRQ_PIOS_FIS);
 773}
 774
 775static bool ahci_write_fis_d2h(AHCIDevice *ad)
 776{
 777    AHCIPortRegs *pr = &ad->port_regs;
 778    uint8_t *d2h_fis;
 779    int i;
 780    IDEState *s = &ad->port.ifs[0];
 781
 782    if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
 783        return false;
 784    }
 785
 786    d2h_fis = &ad->res_fis[RES_FIS_RFIS];
 787
 788    d2h_fis[0] = SATA_FIS_TYPE_REGISTER_D2H;
 789    d2h_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
 790    d2h_fis[2] = s->status;
 791    d2h_fis[3] = s->error;
 792
 793    d2h_fis[4] = s->sector;
 794    d2h_fis[5] = s->lcyl;
 795    d2h_fis[6] = s->hcyl;
 796    d2h_fis[7] = s->select;
 797    d2h_fis[8] = s->hob_sector;
 798    d2h_fis[9] = s->hob_lcyl;
 799    d2h_fis[10] = s->hob_hcyl;
 800    d2h_fis[11] = 0;
 801    d2h_fis[12] = s->nsector & 0xFF;
 802    d2h_fis[13] = (s->nsector >> 8) & 0xFF;
 803    for (i = 14; i < 20; i++) {
 804        d2h_fis[i] = 0;
 805    }
 806
 807    /* Update shadow registers: */
 808    pr->tfdata = (ad->port.ifs[0].error << 8) |
 809        ad->port.ifs[0].status;
 810
 811    if (d2h_fis[2] & ERR_STAT) {
 812        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
 813    }
 814
 815    ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS);
 816    return true;
 817}
 818
 819static int prdt_tbl_entry_size(const AHCI_SG *tbl)
 820{
 821    /* flags_size is zero-based */
 822    return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1;
 823}
 824
 825/**
 826 * Fetch entries in a guest-provided PRDT and convert it into a QEMU SGlist.
 827 * @ad: The AHCIDevice for whom we are building the SGList.
 828 * @sglist: The SGList target to add PRD entries to.
 829 * @cmd: The AHCI Command Header that describes where the PRDT is.
 830 * @limit: The remaining size of the S/ATA transaction, in bytes.
 831 * @offset: The number of bytes already transferred, in bytes.
 832 *
 833 * The AHCI PRDT can describe up to 256GiB. S/ATA only support transactions of
 834 * up to 32MiB as of ATA8-ACS3 rev 1b, assuming a 512 byte sector size. We stop
 835 * building the sglist from the PRDT as soon as we hit @limit bytes,
 836 * which is <= INT32_MAX/2GiB.
 837 */
 838static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist,
 839                                AHCICmdHdr *cmd, int64_t limit, uint64_t offset)
 840{
 841    uint16_t opts = le16_to_cpu(cmd->opts);
 842    uint16_t prdtl = le16_to_cpu(cmd->prdtl);
 843    uint64_t cfis_addr = le64_to_cpu(cmd->tbl_addr);
 844    uint64_t prdt_addr = cfis_addr + 0x80;
 845    dma_addr_t prdt_len = (prdtl * sizeof(AHCI_SG));
 846    dma_addr_t real_prdt_len = prdt_len;
 847    uint8_t *prdt;
 848    int i;
 849    int r = 0;
 850    uint64_t sum = 0;
 851    int off_idx = -1;
 852    int64_t off_pos = -1;
 853    int tbl_entry_size;
 854    IDEBus *bus = &ad->port;
 855    BusState *qbus = BUS(bus);
 856
 857    if (!prdtl) {
 858        DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);
 859        return -1;
 860    }
 861
 862    /* map PRDT */
 863    if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,
 864                                DMA_DIRECTION_TO_DEVICE))){
 865        DPRINTF(ad->port_no, "map failed\n");
 866        return -1;
 867    }
 868
 869    if (prdt_len < real_prdt_len) {
 870        DPRINTF(ad->port_no, "mapped less than expected\n");
 871        r = -1;
 872        goto out;
 873    }
 874
 875    /* Get entries in the PRDT, init a qemu sglist accordingly */
 876    if (prdtl > 0) {
 877        AHCI_SG *tbl = (AHCI_SG *)prdt;
 878        sum = 0;
 879        for (i = 0; i < prdtl; i++) {
 880            tbl_entry_size = prdt_tbl_entry_size(&tbl[i]);
 881            if (offset < (sum + tbl_entry_size)) {
 882                off_idx = i;
 883                off_pos = offset - sum;
 884                break;
 885            }
 886            sum += tbl_entry_size;
 887        }
 888        if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {
 889            DPRINTF(ad->port_no, "%s: Incorrect offset! "
 890                            "off_idx: %d, off_pos: %"PRId64"\n",
 891                            __func__, off_idx, off_pos);
 892            r = -1;
 893            goto out;
 894        }
 895
 896        qemu_sglist_init(sglist, qbus->parent, (prdtl - off_idx),
 897                         ad->hba->as);
 898        qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr) + off_pos,
 899                        MIN(prdt_tbl_entry_size(&tbl[off_idx]) - off_pos,
 900                            limit));
 901
 902        for (i = off_idx + 1; i < prdtl && sglist->size < limit; i++) {
 903            qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
 904                            MIN(prdt_tbl_entry_size(&tbl[i]),
 905                                limit - sglist->size));
 906        }
 907    }
 908
 909out:
 910    dma_memory_unmap(ad->hba->as, prdt, prdt_len,
 911                     DMA_DIRECTION_TO_DEVICE, prdt_len);
 912    return r;
 913}
 914
 915static void ncq_err(NCQTransferState *ncq_tfs)
 916{
 917    IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
 918
 919    ide_state->error = ABRT_ERR;
 920    ide_state->status = READY_STAT | ERR_STAT;
 921    ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
 922    ncq_tfs->used = 0;
 923}
 924
 925static void ncq_finish(NCQTransferState *ncq_tfs)
 926{
 927    /* If we didn't error out, set our finished bit. Errored commands
 928     * do not get a bit set for the SDB FIS ACT register, nor do they
 929     * clear the outstanding bit in scr_act (PxSACT). */
 930    if (!(ncq_tfs->drive->port_regs.scr_err & (1 << ncq_tfs->tag))) {
 931        ncq_tfs->drive->finished |= (1 << ncq_tfs->tag);
 932    }
 933
 934    ahci_write_fis_sdb(ncq_tfs->drive->hba, ncq_tfs);
 935
 936    DPRINTF(ncq_tfs->drive->port_no, "NCQ transfer tag %d finished\n",
 937            ncq_tfs->tag);
 938
 939    block_acct_done(blk_get_stats(ncq_tfs->drive->port.ifs[0].blk),
 940                    &ncq_tfs->acct);
 941    qemu_sglist_destroy(&ncq_tfs->sglist);
 942    ncq_tfs->used = 0;
 943}
 944
 945static void ncq_cb(void *opaque, int ret)
 946{
 947    NCQTransferState *ncq_tfs = (NCQTransferState *)opaque;
 948    IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
 949
 950    if (ret == -ECANCELED) {
 951        return;
 952    }
 953
 954    if (ret < 0) {
 955        bool is_read = ncq_tfs->cmd == READ_FPDMA_QUEUED;
 956        BlockErrorAction action = blk_get_error_action(ide_state->blk,
 957                                                       is_read, -ret);
 958        if (action == BLOCK_ERROR_ACTION_STOP) {
 959            ncq_tfs->halt = true;
 960            ide_state->bus->error_status = IDE_RETRY_HBA;
 961        } else if (action == BLOCK_ERROR_ACTION_REPORT) {
 962            ncq_err(ncq_tfs);
 963        }
 964        blk_error_action(ide_state->blk, action, is_read, -ret);
 965    } else {
 966        ide_state->status = READY_STAT | SEEK_STAT;
 967    }
 968
 969    if (!ncq_tfs->halt) {
 970        ncq_finish(ncq_tfs);
 971    }
 972}
 973
 974static int is_ncq(uint8_t ata_cmd)
 975{
 976    /* Based on SATA 3.2 section 13.6.3.2 */
 977    switch (ata_cmd) {
 978    case READ_FPDMA_QUEUED:
 979    case WRITE_FPDMA_QUEUED:
 980    case NCQ_NON_DATA:
 981    case RECEIVE_FPDMA_QUEUED:
 982    case SEND_FPDMA_QUEUED:
 983        return 1;
 984    default:
 985        return 0;
 986    }
 987}
 988
 989static void execute_ncq_command(NCQTransferState *ncq_tfs)
 990{
 991    AHCIDevice *ad = ncq_tfs->drive;
 992    IDEState *ide_state = &ad->port.ifs[0];
 993    int port = ad->port_no;
 994
 995    g_assert(is_ncq(ncq_tfs->cmd));
 996    ncq_tfs->halt = false;
 997
 998    switch (ncq_tfs->cmd) {
 999    case READ_FPDMA_QUEUED:
1000        DPRINTF(port, "NCQ reading %d sectors from LBA %"PRId64", tag %d\n",
1001                ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
1002
1003        DPRINTF(port, "tag %d aio read %"PRId64"\n",
1004                ncq_tfs->tag, ncq_tfs->lba);
1005
1006        dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1007                       &ncq_tfs->sglist, BLOCK_ACCT_READ);
1008        ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
1009                                      ncq_tfs->lba, ncq_cb, ncq_tfs);
1010        break;
1011    case WRITE_FPDMA_QUEUED:
1012        DPRINTF(port, "NCQ writing %d sectors to LBA %"PRId64", tag %d\n",
1013                ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
1014
1015        DPRINTF(port, "tag %d aio write %"PRId64"\n",
1016                ncq_tfs->tag, ncq_tfs->lba);
1017
1018        dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1019                       &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
1020        ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
1021                                       ncq_tfs->lba, ncq_cb, ncq_tfs);
1022        break;
1023    default:
1024        DPRINTF(port, "error: unsupported NCQ command (0x%02x) received\n",
1025                ncq_tfs->cmd);
1026        qemu_sglist_destroy(&ncq_tfs->sglist);
1027        ncq_err(ncq_tfs);
1028    }
1029}
1030
1031
1032static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
1033                                uint8_t slot)
1034{
1035    AHCIDevice *ad = &s->dev[port];
1036    IDEState *ide_state = &ad->port.ifs[0];
1037    NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;
1038    uint8_t tag = ncq_fis->tag >> 3;
1039    NCQTransferState *ncq_tfs = &ad->ncq_tfs[tag];
1040    size_t size;
1041
1042    g_assert(is_ncq(ncq_fis->command));
1043    if (ncq_tfs->used) {
1044        /* error - already in use */
1045        fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);
1046        return;
1047    }
1048
1049    ncq_tfs->used = 1;
1050    ncq_tfs->drive = ad;
1051    ncq_tfs->slot = slot;
1052    ncq_tfs->cmdh = &((AHCICmdHdr *)ad->lst)[slot];
1053    ncq_tfs->cmd = ncq_fis->command;
1054    ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
1055                   ((uint64_t)ncq_fis->lba4 << 32) |
1056                   ((uint64_t)ncq_fis->lba3 << 24) |
1057                   ((uint64_t)ncq_fis->lba2 << 16) |
1058                   ((uint64_t)ncq_fis->lba1 << 8) |
1059                   (uint64_t)ncq_fis->lba0;
1060    ncq_tfs->tag = tag;
1061
1062    /* Sanity-check the NCQ packet */
1063    if (tag != slot) {
1064        DPRINTF(port, "Warn: NCQ slot (%d) did not match the given tag (%d)\n",
1065                slot, tag);
1066    }
1067
1068    if (ncq_fis->aux0 || ncq_fis->aux1 || ncq_fis->aux2 || ncq_fis->aux3) {
1069        DPRINTF(port, "Warn: Attempt to use NCQ auxiliary fields.\n");
1070    }
1071    if (ncq_fis->prio || ncq_fis->icc) {
1072        DPRINTF(port, "Warn: Unsupported attempt to use PRIO/ICC fields\n");
1073    }
1074    if (ncq_fis->fua & NCQ_FIS_FUA_MASK) {
1075        DPRINTF(port, "Warn: Unsupported attempt to use Force Unit Access\n");
1076    }
1077    if (ncq_fis->tag & NCQ_FIS_RARC_MASK) {
1078        DPRINTF(port, "Warn: Unsupported attempt to use Rebuild Assist\n");
1079    }
1080
1081    ncq_tfs->sector_count = ((ncq_fis->sector_count_high << 8) |
1082                             ncq_fis->sector_count_low);
1083    if (!ncq_tfs->sector_count) {
1084        ncq_tfs->sector_count = 0x10000;
1085    }
1086    size = ncq_tfs->sector_count * 512;
1087    ahci_populate_sglist(ad, &ncq_tfs->sglist, ncq_tfs->cmdh, size, 0);
1088
1089    if (ncq_tfs->sglist.size < size) {
1090        error_report("ahci: PRDT length for NCQ command (0x%zx) "
1091                     "is smaller than the requested size (0x%zx)",
1092                     ncq_tfs->sglist.size, size);
1093        qemu_sglist_destroy(&ncq_tfs->sglist);
1094        ncq_err(ncq_tfs);
1095        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_OVERFLOW);
1096        return;
1097    } else if (ncq_tfs->sglist.size != size) {
1098        DPRINTF(port, "Warn: PRDTL (0x%zx)"
1099                " does not match requested size (0x%zx)",
1100                ncq_tfs->sglist.size, size);
1101    }
1102
1103    DPRINTF(port, "NCQ transfer LBA from %"PRId64" to %"PRId64", "
1104            "drive max %"PRId64"\n",
1105            ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 1,
1106            ide_state->nb_sectors - 1);
1107
1108    execute_ncq_command(ncq_tfs);
1109}
1110
1111static AHCICmdHdr *get_cmd_header(AHCIState *s, uint8_t port, uint8_t slot)
1112{
1113    if (port >= s->ports || slot >= AHCI_MAX_CMDS) {
1114        return NULL;
1115    }
1116
1117    return s->dev[port].lst ? &((AHCICmdHdr *)s->dev[port].lst)[slot] : NULL;
1118}
1119
1120static void handle_reg_h2d_fis(AHCIState *s, int port,
1121                               uint8_t slot, uint8_t *cmd_fis)
1122{
1123    IDEState *ide_state = &s->dev[port].port.ifs[0];
1124    AHCICmdHdr *cmd = get_cmd_header(s, port, slot);
1125    uint16_t opts = le16_to_cpu(cmd->opts);
1126
1127    if (cmd_fis[1] & 0x0F) {
1128        DPRINTF(port, "Port Multiplier not supported."
1129                " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1130                cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1131        return;
1132    }
1133
1134    if (cmd_fis[1] & 0x70) {
1135        DPRINTF(port, "Reserved flags set in H2D Register FIS."
1136                " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1137                cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1138        return;
1139    }
1140
1141    if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {
1142        switch (s->dev[port].port_state) {
1143        case STATE_RUN:
1144            if (cmd_fis[15] & ATA_SRST) {
1145                s->dev[port].port_state = STATE_RESET;
1146            }
1147            break;
1148        case STATE_RESET:
1149            if (!(cmd_fis[15] & ATA_SRST)) {
1150                ahci_reset_port(s, port);
1151            }
1152            break;
1153        }
1154        return;
1155    }
1156
1157    /* Check for NCQ command */
1158    if (is_ncq(cmd_fis[2])) {
1159        process_ncq_command(s, port, cmd_fis, slot);
1160        return;
1161    }
1162
1163    /* Decompose the FIS:
1164     * AHCI does not interpret FIS packets, it only forwards them.
1165     * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.
1166     * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.
1167     *
1168     * ATA4 describes sector number for LBA28/CHS commands.
1169     * ATA6 describes sector number for LBA48 commands.
1170     * ATA8 deprecates CHS fully, describing only LBA28/48.
1171     *
1172     * We dutifully convert the FIS into IDE registers, and allow the
1173     * core layer to interpret them as needed. */
1174    ide_state->feature = cmd_fis[3];
1175    ide_state->sector = cmd_fis[4];      /* LBA 7:0 */
1176    ide_state->lcyl = cmd_fis[5];        /* LBA 15:8  */
1177    ide_state->hcyl = cmd_fis[6];        /* LBA 23:16 */
1178    ide_state->select = cmd_fis[7];      /* LBA 27:24 (LBA28) */
1179    ide_state->hob_sector = cmd_fis[8];  /* LBA 31:24 */
1180    ide_state->hob_lcyl = cmd_fis[9];    /* LBA 39:32 */
1181    ide_state->hob_hcyl = cmd_fis[10];   /* LBA 47:40 */
1182    ide_state->hob_feature = cmd_fis[11];
1183    ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
1184    /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */
1185    /* 15: Only valid when UPDATE_COMMAND not set. */
1186
1187    /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
1188     * table to ide_state->io_buffer */
1189    if (opts & AHCI_CMD_ATAPI) {
1190        memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
1191        debug_print_fis(ide_state->io_buffer, 0x10);
1192        s->dev[port].done_atapi_packet = false;
1193        /* XXX send PIO setup FIS */
1194    }
1195
1196    ide_state->error = 0;
1197
1198    /* Reset transferred byte counter */
1199    cmd->status = 0;
1200
1201    /* We're ready to process the command in FIS byte 2. */
1202    ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);
1203}
1204
1205static int handle_cmd(AHCIState *s, int port, uint8_t slot)
1206{
1207    IDEState *ide_state;
1208    uint64_t tbl_addr;
1209    AHCICmdHdr *cmd;
1210    uint8_t *cmd_fis;
1211    dma_addr_t cmd_len;
1212
1213    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1214        /* Engine currently busy, try again later */
1215        DPRINTF(port, "engine busy\n");
1216        return -1;
1217    }
1218
1219    if (!s->dev[port].lst) {
1220        DPRINTF(port, "error: lst not given but cmd handled");
1221        return -1;
1222    }
1223    cmd = get_cmd_header(s, port, slot);
1224    /* remember current slot handle for later */
1225    s->dev[port].cur_cmd = cmd;
1226
1227    /* The device we are working for */
1228    ide_state = &s->dev[port].port.ifs[0];
1229    if (!ide_state->blk) {
1230        DPRINTF(port, "error: guest accessed unused port");
1231        return -1;
1232    }
1233
1234    tbl_addr = le64_to_cpu(cmd->tbl_addr);
1235    cmd_len = 0x80;
1236    cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,
1237                             DMA_DIRECTION_FROM_DEVICE);
1238    if (!cmd_fis) {
1239        DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
1240        return -1;
1241    } else if (cmd_len != 0x80) {
1242        ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR);
1243        DPRINTF(port, "error: dma_memory_map failed: "
1244                "(len(%02"PRIx64") != 0x80)\n",
1245                cmd_len);
1246        goto out;
1247    }
1248    debug_print_fis(cmd_fis, 0x80);
1249
1250    switch (cmd_fis[0]) {
1251        case SATA_FIS_TYPE_REGISTER_H2D:
1252            handle_reg_h2d_fis(s, port, slot, cmd_fis);
1253            break;
1254        default:
1255            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
1256                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
1257                          cmd_fis[2]);
1258            break;
1259    }
1260
1261out:
1262    dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,
1263                     cmd_len);
1264
1265    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1266        /* async command, complete later */
1267        s->dev[port].busy_slot = slot;
1268        return -1;
1269    }
1270
1271    /* done handling the command */
1272    return 0;
1273}
1274
1275/* DMA dev <-> ram */
1276static void ahci_start_transfer(IDEDMA *dma)
1277{
1278    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1279    IDEState *s = &ad->port.ifs[0];
1280    uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
1281    /* write == ram -> device */
1282    uint16_t opts = le16_to_cpu(ad->cur_cmd->opts);
1283    int is_write = opts & AHCI_CMD_WRITE;
1284    int is_atapi = opts & AHCI_CMD_ATAPI;
1285    int has_sglist = 0;
1286
1287    if (is_atapi && !ad->done_atapi_packet) {
1288        /* already prepopulated iobuffer */
1289        ad->done_atapi_packet = true;
1290        size = 0;
1291        goto out;
1292    }
1293
1294    if (ahci_dma_prepare_buf(dma, size)) {
1295        has_sglist = 1;
1296    }
1297
1298    DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",
1299            is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",
1300            has_sglist ? "" : "o");
1301
1302    if (has_sglist && size) {
1303        if (is_write) {
1304            dma_buf_write(s->data_ptr, size, &s->sg);
1305        } else {
1306            dma_buf_read(s->data_ptr, size, &s->sg);
1307        }
1308    }
1309
1310out:
1311    /* declare that we processed everything */
1312    s->data_ptr = s->data_end;
1313
1314    /* Update number of transferred bytes, destroy sglist */
1315    dma_buf_commit(s, size);
1316
1317    s->end_transfer_func(s);
1318
1319    if (!(s->status & DRQ_STAT)) {
1320        /* done with PIO send/receive */
1321        ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));
1322    }
1323}
1324
1325static void ahci_start_dma(IDEDMA *dma, IDEState *s,
1326                           BlockCompletionFunc *dma_cb)
1327{
1328    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1329    DPRINTF(ad->port_no, "\n");
1330    s->io_buffer_offset = 0;
1331    dma_cb(s, 0);
1332}
1333
1334static void ahci_restart_dma(IDEDMA *dma)
1335{
1336    /* Nothing to do, ahci_start_dma already resets s->io_buffer_offset.  */
1337}
1338
1339/**
1340 * IDE/PIO restarts are handled by the core layer, but NCQ commands
1341 * need an extra kick from the AHCI HBA.
1342 */
1343static void ahci_restart(IDEDMA *dma)
1344{
1345    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1346    int i;
1347
1348    for (i = 0; i < AHCI_MAX_CMDS; i++) {
1349        NCQTransferState *ncq_tfs = &ad->ncq_tfs[i];
1350        if (ncq_tfs->halt) {
1351            execute_ncq_command(ncq_tfs);
1352        }
1353    }
1354}
1355
1356/**
1357 * Called in DMA and PIO R/W chains to read the PRDT.
1358 * Not shared with NCQ pathways.
1359 */
1360static int32_t ahci_dma_prepare_buf(IDEDMA *dma, int32_t limit)
1361{
1362    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1363    IDEState *s = &ad->port.ifs[0];
1364
1365    if (ahci_populate_sglist(ad, &s->sg, ad->cur_cmd,
1366                             limit, s->io_buffer_offset) == -1) {
1367        DPRINTF(ad->port_no, "ahci_dma_prepare_buf failed.\n");
1368        return -1;
1369    }
1370    s->io_buffer_size = s->sg.size;
1371
1372    DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
1373    return s->io_buffer_size;
1374}
1375
1376/**
1377 * Updates the command header with a bytes-read value.
1378 * Called via dma_buf_commit, for both DMA and PIO paths.
1379 * sglist destruction is handled within dma_buf_commit.
1380 */
1381static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes)
1382{
1383    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1384
1385    tx_bytes += le32_to_cpu(ad->cur_cmd->status);
1386    ad->cur_cmd->status = cpu_to_le32(tx_bytes);
1387}
1388
1389static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
1390{
1391    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1392    IDEState *s = &ad->port.ifs[0];
1393    uint8_t *p = s->io_buffer + s->io_buffer_index;
1394    int l = s->io_buffer_size - s->io_buffer_index;
1395
1396    if (ahci_populate_sglist(ad, &s->sg, ad->cur_cmd, l, s->io_buffer_offset)) {
1397        return 0;
1398    }
1399
1400    if (is_write) {
1401        dma_buf_read(p, l, &s->sg);
1402    } else {
1403        dma_buf_write(p, l, &s->sg);
1404    }
1405
1406    /* free sglist, update byte count */
1407    dma_buf_commit(s, l);
1408
1409    s->io_buffer_index += l;
1410
1411    DPRINTF(ad->port_no, "len=%#x\n", l);
1412
1413    return 1;
1414}
1415
1416static void ahci_cmd_done(IDEDMA *dma)
1417{
1418    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1419
1420    DPRINTF(ad->port_no, "cmd done\n");
1421
1422    /* update d2h status */
1423    ahci_write_fis_d2h(ad);
1424
1425    if (!ad->check_bh) {
1426        /* maybe we still have something to process, check later */
1427        ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad);
1428        qemu_bh_schedule(ad->check_bh);
1429    }
1430}
1431
1432static void ahci_irq_set(void *opaque, int n, int level)
1433{
1434}
1435
1436static const IDEDMAOps ahci_dma_ops = {
1437    .start_dma = ahci_start_dma,
1438    .restart = ahci_restart,
1439    .restart_dma = ahci_restart_dma,
1440    .start_transfer = ahci_start_transfer,
1441    .prepare_buf = ahci_dma_prepare_buf,
1442    .commit_buf = ahci_commit_buf,
1443    .rw_buf = ahci_dma_rw_buf,
1444    .cmd_done = ahci_cmd_done,
1445};
1446
1447void ahci_init(AHCIState *s, DeviceState *qdev)
1448{
1449    s->container = qdev;
1450    /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1451    memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s,
1452                          "ahci", AHCI_MEM_BAR_SIZE);
1453    memory_region_init_io(&s->idp, OBJECT(qdev), &ahci_idp_ops, s,
1454                          "ahci-idp", 32);
1455}
1456
1457void ahci_realize(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports)
1458{
1459    qemu_irq *irqs;
1460    int i;
1461
1462    s->as = as;
1463    s->ports = ports;
1464    s->dev = g_new0(AHCIDevice, ports);
1465    ahci_reg_init(s);
1466    irqs = qemu_allocate_irqs(ahci_irq_set, s, s->ports);
1467    for (i = 0; i < s->ports; i++) {
1468        AHCIDevice *ad = &s->dev[i];
1469
1470        ide_bus_new(&ad->port, sizeof(ad->port), qdev, i, 1);
1471        ide_init2(&ad->port, irqs[i]);
1472
1473        ad->hba = s;
1474        ad->port_no = i;
1475        ad->port.dma = &ad->dma;
1476        ad->port.dma->ops = &ahci_dma_ops;
1477        ide_register_restart_cb(&ad->port);
1478    }
1479}
1480
1481void ahci_uninit(AHCIState *s)
1482{
1483    g_free(s->dev);
1484}
1485
1486void ahci_reset(AHCIState *s)
1487{
1488    AHCIPortRegs *pr;
1489    int i;
1490
1491    s->control_regs.irqstatus = 0;
1492    /* AHCI Enable (AE)
1493     * The implementation of this bit is dependent upon the value of the
1494     * CAP.SAM bit. If CAP.SAM is '0', then GHC.AE shall be read-write and
1495     * shall have a reset value of '0'. If CAP.SAM is '1', then AE shall be
1496     * read-only and shall have a reset value of '1'.
1497     *
1498     * We set HOST_CAP_AHCI so we must enable AHCI at reset.
1499     */
1500    s->control_regs.ghc = HOST_CTL_AHCI_EN;
1501
1502    for (i = 0; i < s->ports; i++) {
1503        pr = &s->dev[i].port_regs;
1504        pr->irq_stat = 0;
1505        pr->irq_mask = 0;
1506        pr->scr_ctl = 0;
1507        pr->cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
1508        ahci_reset_port(s, i);
1509    }
1510}
1511
1512static const VMStateDescription vmstate_ncq_tfs = {
1513    .name = "ncq state",
1514    .version_id = 1,
1515    .fields = (VMStateField[]) {
1516        VMSTATE_UINT32(sector_count, NCQTransferState),
1517        VMSTATE_UINT64(lba, NCQTransferState),
1518        VMSTATE_UINT8(tag, NCQTransferState),
1519        VMSTATE_UINT8(cmd, NCQTransferState),
1520        VMSTATE_UINT8(slot, NCQTransferState),
1521        VMSTATE_BOOL(used, NCQTransferState),
1522        VMSTATE_BOOL(halt, NCQTransferState),
1523        VMSTATE_END_OF_LIST()
1524    },
1525};
1526
1527static const VMStateDescription vmstate_ahci_device = {
1528    .name = "ahci port",
1529    .version_id = 1,
1530    .fields = (VMStateField[]) {
1531        VMSTATE_IDE_BUS(port, AHCIDevice),
1532        VMSTATE_IDE_DRIVE(port.ifs[0], AHCIDevice),
1533        VMSTATE_UINT32(port_state, AHCIDevice),
1534        VMSTATE_UINT32(finished, AHCIDevice),
1535        VMSTATE_UINT32(port_regs.lst_addr, AHCIDevice),
1536        VMSTATE_UINT32(port_regs.lst_addr_hi, AHCIDevice),
1537        VMSTATE_UINT32(port_regs.fis_addr, AHCIDevice),
1538        VMSTATE_UINT32(port_regs.fis_addr_hi, AHCIDevice),
1539        VMSTATE_UINT32(port_regs.irq_stat, AHCIDevice),
1540        VMSTATE_UINT32(port_regs.irq_mask, AHCIDevice),
1541        VMSTATE_UINT32(port_regs.cmd, AHCIDevice),
1542        VMSTATE_UINT32(port_regs.tfdata, AHCIDevice),
1543        VMSTATE_UINT32(port_regs.sig, AHCIDevice),
1544        VMSTATE_UINT32(port_regs.scr_stat, AHCIDevice),
1545        VMSTATE_UINT32(port_regs.scr_ctl, AHCIDevice),
1546        VMSTATE_UINT32(port_regs.scr_err, AHCIDevice),
1547        VMSTATE_UINT32(port_regs.scr_act, AHCIDevice),
1548        VMSTATE_UINT32(port_regs.cmd_issue, AHCIDevice),
1549        VMSTATE_BOOL(done_atapi_packet, AHCIDevice),
1550        VMSTATE_INT32(busy_slot, AHCIDevice),
1551        VMSTATE_BOOL(init_d2h_sent, AHCIDevice),
1552        VMSTATE_STRUCT_ARRAY(ncq_tfs, AHCIDevice, AHCI_MAX_CMDS,
1553                             1, vmstate_ncq_tfs, NCQTransferState),
1554        VMSTATE_END_OF_LIST()
1555    },
1556};
1557
1558static int ahci_state_post_load(void *opaque, int version_id)
1559{
1560    int i, j;
1561    struct AHCIDevice *ad;
1562    NCQTransferState *ncq_tfs;
1563    AHCIPortRegs *pr;
1564    AHCIState *s = opaque;
1565
1566    for (i = 0; i < s->ports; i++) {
1567        ad = &s->dev[i];
1568        pr = &ad->port_regs;
1569
1570        if (!(pr->cmd & PORT_CMD_START) && (pr->cmd & PORT_CMD_LIST_ON)) {
1571            error_report("AHCI: DMA engine should be off, but status bit "
1572                         "indicates it is still running.");
1573            return -1;
1574        }
1575        if (!(pr->cmd & PORT_CMD_FIS_RX) && (pr->cmd & PORT_CMD_FIS_ON)) {
1576            error_report("AHCI: FIS RX engine should be off, but status bit "
1577                         "indicates it is still running.");
1578            return -1;
1579        }
1580
1581        /* After a migrate, the DMA/FIS engines are "off" and
1582         * need to be conditionally restarted */
1583        pr->cmd &= ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON);
1584        if (ahci_cond_start_engines(ad) != 0) {
1585            return -1;
1586        }
1587
1588        for (j = 0; j < AHCI_MAX_CMDS; j++) {
1589            ncq_tfs = &ad->ncq_tfs[j];
1590            ncq_tfs->drive = ad;
1591
1592            if (ncq_tfs->used != ncq_tfs->halt) {
1593                return -1;
1594            }
1595            if (!ncq_tfs->halt) {
1596                continue;
1597            }
1598            if (!is_ncq(ncq_tfs->cmd)) {
1599                return -1;
1600            }
1601            if (ncq_tfs->slot != ncq_tfs->tag) {
1602                return -1;
1603            }
1604            /* If ncq_tfs->halt is justly set, the engine should be engaged,
1605             * and the command list buffer should be mapped. */
1606            ncq_tfs->cmdh = get_cmd_header(s, i, ncq_tfs->slot);
1607            if (!ncq_tfs->cmdh) {
1608                return -1;
1609            }
1610            ahci_populate_sglist(ncq_tfs->drive, &ncq_tfs->sglist,
1611                                 ncq_tfs->cmdh, ncq_tfs->sector_count * 512,
1612                                 0);
1613            if (ncq_tfs->sector_count != ncq_tfs->sglist.size >> 9) {
1614                return -1;
1615            }
1616        }
1617
1618
1619        /*
1620         * If an error is present, ad->busy_slot will be valid and not -1.
1621         * In this case, an operation is waiting to resume and will re-check
1622         * for additional AHCI commands to execute upon completion.
1623         *
1624         * In the case where no error was present, busy_slot will be -1,
1625         * and we should check to see if there are additional commands waiting.
1626         */
1627        if (ad->busy_slot == -1) {
1628            check_cmd(s, i);
1629        } else {
1630            /* We are in the middle of a command, and may need to access
1631             * the command header in guest memory again. */
1632            if (ad->busy_slot < 0 || ad->busy_slot >= AHCI_MAX_CMDS) {
1633                return -1;
1634            }
1635            ad->cur_cmd = get_cmd_header(s, i, ad->busy_slot);
1636        }
1637    }
1638
1639    return 0;
1640}
1641
1642const VMStateDescription vmstate_ahci = {
1643    .name = "ahci",
1644    .version_id = 1,
1645    .post_load = ahci_state_post_load,
1646    .fields = (VMStateField[]) {
1647        VMSTATE_STRUCT_VARRAY_POINTER_INT32(dev, AHCIState, ports,
1648                                     vmstate_ahci_device, AHCIDevice),
1649        VMSTATE_UINT32(control_regs.cap, AHCIState),
1650        VMSTATE_UINT32(control_regs.ghc, AHCIState),
1651        VMSTATE_UINT32(control_regs.irqstatus, AHCIState),
1652        VMSTATE_UINT32(control_regs.impl, AHCIState),
1653        VMSTATE_UINT32(control_regs.version, AHCIState),
1654        VMSTATE_UINT32(idp_index, AHCIState),
1655        VMSTATE_INT32_EQUAL(ports, AHCIState),
1656        VMSTATE_END_OF_LIST()
1657    },
1658};
1659
1660static const VMStateDescription vmstate_sysbus_ahci = {
1661    .name = "sysbus-ahci",
1662    .fields = (VMStateField[]) {
1663        VMSTATE_AHCI(ahci, SysbusAHCIState),
1664        VMSTATE_END_OF_LIST()
1665    },
1666};
1667
1668static void sysbus_ahci_reset(DeviceState *dev)
1669{
1670    SysbusAHCIState *s = SYSBUS_AHCI(dev);
1671
1672    ahci_reset(&s->ahci);
1673}
1674
1675static void sysbus_ahci_init(Object *obj)
1676{
1677    SysbusAHCIState *s = SYSBUS_AHCI(obj);
1678    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
1679
1680    ahci_init(&s->ahci, DEVICE(obj));
1681
1682    sysbus_init_mmio(sbd, &s->ahci.mem);
1683    sysbus_init_irq(sbd, &s->ahci.irq);
1684}
1685
1686static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
1687{
1688    SysbusAHCIState *s = SYSBUS_AHCI(dev);
1689
1690    ahci_realize(&s->ahci, dev, &address_space_memory, s->num_ports);
1691}
1692
1693static Property sysbus_ahci_properties[] = {
1694    DEFINE_PROP_UINT32("num-ports", SysbusAHCIState, num_ports, 1),
1695    DEFINE_PROP_END_OF_LIST(),
1696};
1697
1698static void sysbus_ahci_class_init(ObjectClass *klass, void *data)
1699{
1700    DeviceClass *dc = DEVICE_CLASS(klass);
1701
1702    dc->realize = sysbus_ahci_realize;
1703    dc->vmsd = &vmstate_sysbus_ahci;
1704    dc->props = sysbus_ahci_properties;
1705    dc->reset = sysbus_ahci_reset;
1706    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1707}
1708
1709static const TypeInfo sysbus_ahci_info = {
1710    .name          = TYPE_SYSBUS_AHCI,
1711    .parent        = TYPE_SYS_BUS_DEVICE,
1712    .instance_size = sizeof(SysbusAHCIState),
1713    .instance_init = sysbus_ahci_init,
1714    .class_init    = sysbus_ahci_class_init,
1715};
1716
1717#define ALLWINNER_AHCI_BISTAFR    ((0xa0 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1718#define ALLWINNER_AHCI_BISTCR     ((0xa4 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1719#define ALLWINNER_AHCI_BISTFCTR   ((0xa8 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1720#define ALLWINNER_AHCI_BISTSR     ((0xac - ALLWINNER_AHCI_MMIO_OFF) / 4)
1721#define ALLWINNER_AHCI_BISTDECR   ((0xb0 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1722#define ALLWINNER_AHCI_DIAGNR0    ((0xb4 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1723#define ALLWINNER_AHCI_DIAGNR1    ((0xb8 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1724#define ALLWINNER_AHCI_OOBR       ((0xbc - ALLWINNER_AHCI_MMIO_OFF) / 4)
1725#define ALLWINNER_AHCI_PHYCS0R    ((0xc0 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1726#define ALLWINNER_AHCI_PHYCS1R    ((0xc4 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1727#define ALLWINNER_AHCI_PHYCS2R    ((0xc8 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1728#define ALLWINNER_AHCI_TIMER1MS   ((0xe0 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1729#define ALLWINNER_AHCI_GPARAM1R   ((0xe8 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1730#define ALLWINNER_AHCI_GPARAM2R   ((0xec - ALLWINNER_AHCI_MMIO_OFF) / 4)
1731#define ALLWINNER_AHCI_PPARAMR    ((0xf0 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1732#define ALLWINNER_AHCI_TESTR      ((0xf4 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1733#define ALLWINNER_AHCI_VERSIONR   ((0xf8 - ALLWINNER_AHCI_MMIO_OFF) / 4)
1734#define ALLWINNER_AHCI_IDR        ((0xfc - ALLWINNER_AHCI_MMIO_OFF) / 4)
1735#define ALLWINNER_AHCI_RWCR       ((0xfc - ALLWINNER_AHCI_MMIO_OFF) / 4)
1736
1737static uint64_t allwinner_ahci_mem_read(void *opaque, hwaddr addr,
1738                                        unsigned size)
1739{
1740    AllwinnerAHCIState *a = opaque;
1741    uint64_t val = a->regs[addr/4];
1742
1743    switch (addr / 4) {
1744    case ALLWINNER_AHCI_PHYCS0R:
1745        val |= 0x2 << 28;
1746        break;
1747    case ALLWINNER_AHCI_PHYCS2R:
1748        val &= ~(0x1 << 24);
1749        break;
1750    }
1751    DPRINTF(-1, "addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 ", size=%d\n",
1752            addr, val, size);
1753    return  val;
1754}
1755
1756static void allwinner_ahci_mem_write(void *opaque, hwaddr addr,
1757                                     uint64_t val, unsigned size)
1758{
1759    AllwinnerAHCIState *a = opaque;
1760
1761    DPRINTF(-1, "addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 ", size=%d\n",
1762            addr, val, size);
1763    a->regs[addr/4] = val;
1764}
1765
1766static const MemoryRegionOps allwinner_ahci_mem_ops = {
1767    .read = allwinner_ahci_mem_read,
1768    .write = allwinner_ahci_mem_write,
1769    .valid.min_access_size = 4,
1770    .valid.max_access_size = 4,
1771    .endianness = DEVICE_LITTLE_ENDIAN,
1772};
1773
1774static void allwinner_ahci_init(Object *obj)
1775{
1776    SysbusAHCIState *s = SYSBUS_AHCI(obj);
1777    AllwinnerAHCIState *a = ALLWINNER_AHCI(obj);
1778
1779    memory_region_init_io(&a->mmio, OBJECT(obj), &allwinner_ahci_mem_ops, a,
1780                          "allwinner-ahci", ALLWINNER_AHCI_MMIO_SIZE);
1781    memory_region_add_subregion(&s->ahci.mem, ALLWINNER_AHCI_MMIO_OFF,
1782                                &a->mmio);
1783}
1784
1785static const VMStateDescription vmstate_allwinner_ahci = {
1786    .name = "allwinner-ahci",
1787    .version_id = 1,
1788    .minimum_version_id = 1,
1789    .fields = (VMStateField[]) {
1790        VMSTATE_UINT32_ARRAY(regs, AllwinnerAHCIState,
1791                             ALLWINNER_AHCI_MMIO_SIZE/4),
1792        VMSTATE_END_OF_LIST()
1793    }
1794};
1795
1796static void allwinner_ahci_class_init(ObjectClass *klass, void *data)
1797{
1798    DeviceClass *dc = DEVICE_CLASS(klass);
1799
1800    dc->vmsd = &vmstate_allwinner_ahci;
1801}
1802
1803static const TypeInfo allwinner_ahci_info = {
1804    .name          = TYPE_ALLWINNER_AHCI,
1805    .parent        = TYPE_SYSBUS_AHCI,
1806    .instance_size = sizeof(AllwinnerAHCIState),
1807    .instance_init = allwinner_ahci_init,
1808    .class_init    = allwinner_ahci_class_init,
1809};
1810
1811static void sysbus_ahci_register_types(void)
1812{
1813    type_register_static(&sysbus_ahci_info);
1814    type_register_static(&allwinner_ahci_info);
1815}
1816
1817type_init(sysbus_ahci_register_types)
1818
1819void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd)
1820{
1821    AHCIPCIState *d = ICH_AHCI(dev);
1822    AHCIState *ahci = &d->ahci;
1823    int i;
1824
1825    for (i = 0; i < ahci->ports; i++) {
1826        if (hd[i] == NULL) {
1827            continue;
1828        }
1829        ide_create_drive(&ahci->dev[i].port, 0, hd[i]);
1830    }
1831
1832}
1833