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