ahci.c 43.4 KB
Newer Older
A
Alexander Graf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * QEMU AHCI Emulation
 *
 * Copyright (c) 2010 qiaochong@loongson.cn
 * Copyright (c) 2010 Roland Elek <elek.roland@gmail.com>
 * Copyright (c) 2010 Sebastian Herbszt <herbszt@gmx.de>
 * Copyright (c) 2010 Alexander Graf <agraf@suse.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <hw/hw.h>
25
#include <hw/pci/msi.h>
P
Paolo Bonzini 已提交
26
#include <hw/i386/pc.h>
27
#include <hw/pci/pci.h>
28
#include <hw/sysbus.h>
A
Alexander Graf 已提交
29

30
#include "monitor/monitor.h"
31
#include "sysemu/block-backend.h"
32
#include "sysemu/dma.h"
A
Alexander Graf 已提交
33 34
#include "internal.h"
#include <hw/ide/pci.h>
S
Sebastian Herbszt 已提交
35
#include <hw/ide/ahci.h>
A
Alexander Graf 已提交
36

37
#define DEBUG_AHCI 0
A
Alexander Graf 已提交
38 39

#define DPRINTF(port, fmt, ...) \
40 41 42 43 44 45
do { \
    if (DEBUG_AHCI) { \
        fprintf(stderr, "ahci: %s: [%d] ", __func__, port); \
        fprintf(stderr, fmt, ## __VA_ARGS__); \
    } \
} while (0)
A
Alexander Graf 已提交
46 47 48 49 50

static void check_cmd(AHCIState *s, int port);
static int handle_cmd(AHCIState *s,int port,int slot);
static void ahci_reset_port(AHCIState *s, int port);
static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis);
51
static void ahci_init_d2h(AHCIDevice *ad);
52 53 54
static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write);
static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes);

A
Alexander Graf 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

static uint32_t  ahci_port_read(AHCIState *s, int port, int offset)
{
    uint32_t val;
    AHCIPortRegs *pr;
    pr = &s->dev[port].port_regs;

    switch (offset) {
    case PORT_LST_ADDR:
        val = pr->lst_addr;
        break;
    case PORT_LST_ADDR_HI:
        val = pr->lst_addr_hi;
        break;
    case PORT_FIS_ADDR:
        val = pr->fis_addr;
        break;
    case PORT_FIS_ADDR_HI:
        val = pr->fis_addr_hi;
        break;
    case PORT_IRQ_STAT:
        val = pr->irq_stat;
        break;
    case PORT_IRQ_MASK:
        val = pr->irq_mask;
        break;
    case PORT_CMD:
        val = pr->cmd;
        break;
    case PORT_TFDATA:
85
        val = pr->tfdata;
A
Alexander Graf 已提交
86 87 88 89 90
        break;
    case PORT_SIG:
        val = pr->sig;
        break;
    case PORT_SCR_STAT:
91
        if (s->dev[port].port.ifs[0].blk) {
A
Alexander Graf 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP |
                  SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE;
        } else {
            val = SATA_SCR_SSTATUS_DET_NODEV;
        }
        break;
    case PORT_SCR_CTL:
        val = pr->scr_ctl;
        break;
    case PORT_SCR_ERR:
        val = pr->scr_err;
        break;
    case PORT_SCR_ACT:
        pr->scr_act &= ~s->dev[port].finished;
        s->dev[port].finished = 0;
        val = pr->scr_act;
        break;
    case PORT_CMD_ISSUE:
        val = pr->cmd_issue;
        break;
    case PORT_RESERVED:
    default:
        val = 0;
    }
    DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
    return val;

}

static void ahci_irq_raise(AHCIState *s, AHCIDevice *dev)
{
123
    AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
R
Rob Herring 已提交
124 125
    PCIDevice *pci_dev =
        (PCIDevice *)object_dynamic_cast(OBJECT(d), TYPE_PCI_DEVICE);
A
Alexander Graf 已提交
126 127 128

    DPRINTF(0, "raise irq\n");

R
Rob Herring 已提交
129
    if (pci_dev && msi_enabled(pci_dev)) {
130
        msi_notify(pci_dev, 0);
A
Alexander Graf 已提交
131 132 133 134 135 136 137
    } else {
        qemu_irq_raise(s->irq);
    }
}

static void ahci_irq_lower(AHCIState *s, AHCIDevice *dev)
{
138
    AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
R
Rob Herring 已提交
139 140
    PCIDevice *pci_dev =
        (PCIDevice *)object_dynamic_cast(OBJECT(d), TYPE_PCI_DEVICE);
A
Alexander Graf 已提交
141 142 143

    DPRINTF(0, "lower irq\n");

R
Rob Herring 已提交
144
    if (!pci_dev || !msi_enabled(pci_dev)) {
A
Alexander Graf 已提交
145 146 147 148 149 150 151 152 153 154
        qemu_irq_lower(s->irq);
    }
}

static void ahci_check_irq(AHCIState *s)
{
    int i;

    DPRINTF(-1, "check irq %#x\n", s->control_regs.irqstatus);

155
    s->control_regs.irqstatus = 0;
156
    for (i = 0; i < s->ports; i++) {
A
Alexander Graf 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        AHCIPortRegs *pr = &s->dev[i].port_regs;
        if (pr->irq_stat & pr->irq_mask) {
            s->control_regs.irqstatus |= (1 << i);
        }
    }

    if (s->control_regs.irqstatus &&
        (s->control_regs.ghc & HOST_CTL_IRQ_EN)) {
            ahci_irq_raise(s, NULL);
    } else {
        ahci_irq_lower(s, NULL);
    }
}

static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d,
                             int irq_type)
{
    DPRINTF(d->port_no, "trigger irq %#x -> %x\n",
            irq_type, d->port_regs.irq_mask & irq_type);

    d->port_regs.irq_stat |= irq_type;
    ahci_check_irq(s);
}

181 182
static void map_page(AddressSpace *as, uint8_t **ptr, uint64_t addr,
                     uint32_t wanted)
A
Alexander Graf 已提交
183
{
A
Avi Kivity 已提交
184
    hwaddr len = wanted;
A
Alexander Graf 已提交
185 186

    if (*ptr) {
187
        dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
A
Alexander Graf 已提交
188 189
    }

190
    *ptr = dma_memory_map(as, addr, &len, DMA_DIRECTION_FROM_DEVICE);
A
Alexander Graf 已提交
191
    if (len < wanted) {
192
        dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
A
Alexander Graf 已提交
193 194 195 196 197 198 199 200 201 202 203 204
        *ptr = NULL;
    }
}

static void  ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)
{
    AHCIPortRegs *pr = &s->dev[port].port_regs;

    DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
    switch (offset) {
        case PORT_LST_ADDR:
            pr->lst_addr = val;
205
            map_page(s->as, &s->dev[port].lst,
A
Alexander Graf 已提交
206 207 208 209 210
                     ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
            s->dev[port].cur_cmd = NULL;
            break;
        case PORT_LST_ADDR_HI:
            pr->lst_addr_hi = val;
211
            map_page(s->as, &s->dev[port].lst,
A
Alexander Graf 已提交
212 213 214 215 216
                     ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
            s->dev[port].cur_cmd = NULL;
            break;
        case PORT_FIS_ADDR:
            pr->fis_addr = val;
217
            map_page(s->as, &s->dev[port].res_fis,
A
Alexander Graf 已提交
218 219 220 221
                     ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
            break;
        case PORT_FIS_ADDR_HI:
            pr->fis_addr_hi = val;
222
            map_page(s->as, &s->dev[port].res_fis,
A
Alexander Graf 已提交
223 224 225 226
                     ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
            break;
        case PORT_IRQ_STAT:
            pr->irq_stat &= ~val;
227
            ahci_check_irq(s);
A
Alexander Graf 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            break;
        case PORT_IRQ_MASK:
            pr->irq_mask = val & 0xfdc000ff;
            ahci_check_irq(s);
            break;
        case PORT_CMD:
            pr->cmd = val & ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON);

            if (pr->cmd & PORT_CMD_START) {
                pr->cmd |= PORT_CMD_LIST_ON;
            }

            if (pr->cmd & PORT_CMD_FIS_RX) {
                pr->cmd |= PORT_CMD_FIS_ON;
            }

244 245 246 247 248 249 250
            /* XXX usually the FIS would be pending on the bus here and
                   issuing deferred until the OS enables FIS receival.
                   Instead, we only submit it once - which works in most
                   cases, but is a hack. */
            if ((pr->cmd & PORT_CMD_FIS_ON) &&
                !s->dev[port].init_d2h_sent) {
                ahci_init_d2h(&s->dev[port]);
251
                s->dev[port].init_d2h_sent = true;
252 253
            }

A
Alexander Graf 已提交
254 255 256
            check_cmd(s, port);
            break;
        case PORT_TFDATA:
257
            /* Read Only. */
A
Alexander Graf 已提交
258 259
            break;
        case PORT_SIG:
260
            /* Read Only */
A
Alexander Graf 已提交
261 262
            break;
        case PORT_SCR_STAT:
263
            /* Read Only */
A
Alexander Graf 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            break;
        case PORT_SCR_CTL:
            if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&
                ((val & AHCI_SCR_SCTL_DET) == 0)) {
                ahci_reset_port(s, port);
            }
            pr->scr_ctl = val;
            break;
        case PORT_SCR_ERR:
            pr->scr_err &= ~val;
            break;
        case PORT_SCR_ACT:
            /* RW1 */
            pr->scr_act |= val;
            break;
        case PORT_CMD_ISSUE:
            pr->cmd_issue |= val;
            check_cmd(s, port);
            break;
        default:
            break;
    }
}

A
Avi Kivity 已提交
288
static uint64_t ahci_mem_read(void *opaque, hwaddr addr,
A
Avi Kivity 已提交
289
                              unsigned size)
A
Alexander Graf 已提交
290
{
A
Avi Kivity 已提交
291
    AHCIState *s = opaque;
A
Alexander Graf 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    uint32_t val = 0;

    if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
        switch (addr) {
        case HOST_CAP:
            val = s->control_regs.cap;
            break;
        case HOST_CTL:
            val = s->control_regs.ghc;
            break;
        case HOST_IRQ_STAT:
            val = s->control_regs.irqstatus;
            break;
        case HOST_PORTS_IMPL:
            val = s->control_regs.impl;
            break;
        case HOST_VERSION:
            val = s->control_regs.version;
            break;
        }

        DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val);
    } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
315 316
               (addr < (AHCI_PORT_REGS_START_ADDR +
                (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
A
Alexander Graf 已提交
317 318 319 320 321 322 323 324 325
        val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
                             addr & AHCI_PORT_ADDR_OFFSET_MASK);
    }

    return val;
}



A
Avi Kivity 已提交
326
static void ahci_mem_write(void *opaque, hwaddr addr,
A
Avi Kivity 已提交
327
                           uint64_t val, unsigned size)
A
Alexander Graf 已提交
328
{
A
Avi Kivity 已提交
329
    AHCIState *s = opaque;
A
Alexander Graf 已提交
330 331 332 333 334 335 336 337 338

    /* Only aligned reads are allowed on AHCI */
    if (addr & 3) {
        fprintf(stderr, "ahci: Mis-aligned write to addr 0x"
                TARGET_FMT_plx "\n", addr);
        return;
    }

    if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
M
Max Filippov 已提交
339
        DPRINTF(-1, "(addr 0x%08X), val 0x%08"PRIX64"\n", (unsigned) addr, val);
A
Alexander Graf 已提交
340 341 342 343 344 345 346 347

        switch (addr) {
            case HOST_CAP: /* R/WO, RO */
                /* FIXME handle R/WO */
                break;
            case HOST_CTL: /* R/W */
                if (val & HOST_CTL_RESET) {
                    DPRINTF(-1, "HBA Reset\n");
J
Jan Kiszka 已提交
348
                    ahci_reset(s);
A
Alexander Graf 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
                } else {
                    s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;
                    ahci_check_irq(s);
                }
                break;
            case HOST_IRQ_STAT: /* R/WC, RO */
                s->control_regs.irqstatus &= ~val;
                ahci_check_irq(s);
                break;
            case HOST_PORTS_IMPL: /* R/WO, RO */
                /* FIXME handle R/WO */
                break;
            case HOST_VERSION: /* RO */
                /* FIXME report write? */
                break;
            default:
                DPRINTF(-1, "write to unknown register 0x%x\n", (unsigned)addr);
        }
    } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
368 369
               (addr < (AHCI_PORT_REGS_START_ADDR +
                (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
A
Alexander Graf 已提交
370 371 372 373 374 375
        ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
                        addr & AHCI_PORT_ADDR_OFFSET_MASK, val);
    }

}

376
static const MemoryRegionOps ahci_mem_ops = {
A
Avi Kivity 已提交
377 378 379
    .read = ahci_mem_read,
    .write = ahci_mem_write,
    .endianness = DEVICE_LITTLE_ENDIAN,
A
Alexander Graf 已提交
380 381
};

A
Avi Kivity 已提交
382
static uint64_t ahci_idp_read(void *opaque, hwaddr addr,
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                              unsigned size)
{
    AHCIState *s = opaque;

    if (addr == s->idp_offset) {
        /* index register */
        return s->idp_index;
    } else if (addr == s->idp_offset + 4) {
        /* data register - do memory read at location selected by index */
        return ahci_mem_read(opaque, s->idp_index, size);
    } else {
        return 0;
    }
}

A
Avi Kivity 已提交
398
static void ahci_idp_write(void *opaque, hwaddr addr,
399 400 401 402 403 404 405 406 407 408 409 410 411
                           uint64_t val, unsigned size)
{
    AHCIState *s = opaque;

    if (addr == s->idp_offset) {
        /* index register - mask off reserved bits */
        s->idp_index = (uint32_t)val & ((AHCI_MEM_BAR_SIZE - 1) & ~3);
    } else if (addr == s->idp_offset + 4) {
        /* data register - do memory write at location selected by index */
        ahci_mem_write(opaque, s->idp_index, val, size);
    }
}

412
static const MemoryRegionOps ahci_idp_ops = {
413 414 415 416 417 418
    .read = ahci_idp_read,
    .write = ahci_idp_write,
    .endianness = DEVICE_LITTLE_ENDIAN,
};


A
Alexander Graf 已提交
419 420 421 422
static void ahci_reg_init(AHCIState *s)
{
    int i;

423
    s->control_regs.cap = (s->ports - 1) |
A
Alexander Graf 已提交
424 425 426 427
                          (AHCI_NUM_COMMAND_SLOTS << 8) |
                          (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) |
                          HOST_CAP_NCQ | HOST_CAP_AHCI;

428
    s->control_regs.impl = (1 << s->ports) - 1;
A
Alexander Graf 已提交
429 430 431

    s->control_regs.version = AHCI_VERSION_1_0;

432
    for (i = 0; i < s->ports; i++) {
A
Alexander Graf 已提交
433 434 435 436 437 438 439 440 441 442 443
        s->dev[i].port_state = STATE_RUN;
    }
}

static void check_cmd(AHCIState *s, int port)
{
    AHCIPortRegs *pr = &s->dev[port].port_regs;
    int slot;

    if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) {
        for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) {
444
            if ((pr->cmd_issue & (1U << slot)) &&
A
Alexander Graf 已提交
445
                !handle_cmd(s, port, slot)) {
446
                pr->cmd_issue &= ~(1U << slot);
A
Alexander Graf 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            }
        }
    }
}

static void ahci_check_cmd_bh(void *opaque)
{
    AHCIDevice *ad = opaque;

    qemu_bh_delete(ad->check_bh);
    ad->check_bh = NULL;

    if ((ad->busy_slot != -1) &&
        !(ad->port.ifs[0].status & (BUSY_STAT|DRQ_STAT))) {
        /* no longer busy */
        ad->port_regs.cmd_issue &= ~(1 << ad->busy_slot);
        ad->busy_slot = -1;
    }

    check_cmd(ad->hba, ad->port_no);
}

469 470
static void ahci_init_d2h(AHCIDevice *ad)
{
471
    uint8_t init_fis[20];
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    IDEState *ide_state = &ad->port.ifs[0];

    memset(init_fis, 0, sizeof(init_fis));

    init_fis[4] = 1;
    init_fis[12] = 1;

    if (ide_state->drive_kind == IDE_CD) {
        init_fis[5] = ide_state->lcyl;
        init_fis[6] = ide_state->hcyl;
    }

    ahci_write_fis_d2h(ad, init_fis);
}

A
Alexander Graf 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
static void ahci_reset_port(AHCIState *s, int port)
{
    AHCIDevice *d = &s->dev[port];
    AHCIPortRegs *pr = &d->port_regs;
    IDEState *ide_state = &d->port.ifs[0];
    int i;

    DPRINTF(port, "reset port\n");

    ide_bus_reset(&d->port);
    ide_state->ncq_queues = AHCI_MAX_CMDS;

    pr->scr_stat = 0;
    pr->scr_err = 0;
    pr->scr_act = 0;
502 503
    pr->tfdata = 0x7F;
    pr->sig = 0xFFFFFFFF;
A
Alexander Graf 已提交
504
    d->busy_slot = -1;
505
    d->init_d2h_sent = false;
A
Alexander Graf 已提交
506 507

    ide_state = &s->dev[port].port.ifs[0];
508
    if (!ide_state->blk) {
A
Alexander Graf 已提交
509 510 511 512 513 514 515 516 517 518 519
        return;
    }

    /* reset ncq queue */
    for (i = 0; i < AHCI_MAX_CMDS; i++) {
        NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[i];
        if (!ncq_tfs->used) {
            continue;
        }

        if (ncq_tfs->aiocb) {
520
            blk_aio_cancel(ncq_tfs->aiocb);
A
Alexander Graf 已提交
521 522 523
            ncq_tfs->aiocb = NULL;
        }

524
        /* Maybe we just finished the request thanks to blk_aio_cancel() */
A
Alexander Graf 已提交
525 526 527 528
        if (!ncq_tfs->used) {
            continue;
        }

A
Alexander Graf 已提交
529 530 531 532 533
        qemu_sglist_destroy(&ncq_tfs->sglist);
        ncq_tfs->used = 0;
    }

    s->dev[port].port_state = STATE_RUN;
534
    if (!ide_state->blk) {
535
        pr->sig = 0;
536
        ide_state->status = SEEK_STAT | WRERR_STAT;
A
Alexander Graf 已提交
537
    } else if (ide_state->drive_kind == IDE_CD) {
538
        pr->sig = SATA_SIGNATURE_CDROM;
A
Alexander Graf 已提交
539 540 541 542 543
        ide_state->lcyl = 0x14;
        ide_state->hcyl = 0xeb;
        DPRINTF(port, "set lcyl = %d\n", ide_state->lcyl);
        ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT;
    } else {
544
        pr->sig = SATA_SIGNATURE_DISK;
A
Alexander Graf 已提交
545 546 547 548
        ide_state->status = SEEK_STAT | WRERR_STAT;
    }

    ide_state->error = 1;
549
    ahci_init_d2h(d);
A
Alexander Graf 已提交
550 551 552 553
}

static void debug_print_fis(uint8_t *fis, int cmd_len)
{
554
#if DEBUG_AHCI
A
Alexander Graf 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    int i;

    fprintf(stderr, "fis:");
    for (i = 0; i < cmd_len; i++) {
        if ((i & 0xf) == 0) {
            fprintf(stderr, "\n%02x:",i);
        }
        fprintf(stderr, "%02x ",fis[i]);
    }
    fprintf(stderr, "\n");
#endif
}

static void ahci_write_fis_sdb(AHCIState *s, int port, uint32_t finished)
{
570 571
    AHCIDevice *ad = &s->dev[port];
    AHCIPortRegs *pr = &ad->port_regs;
A
Alexander Graf 已提交
572
    IDEState *ide_state;
J
John Snow 已提交
573
    SDBFIS *sdb_fis;
A
Alexander Graf 已提交
574 575 576 577 578 579

    if (!s->dev[port].res_fis ||
        !(pr->cmd & PORT_CMD_FIS_RX)) {
        return;
    }

J
John Snow 已提交
580
    sdb_fis = (SDBFIS *)&ad->res_fis[RES_FIS_SDBFIS];
581
    ide_state = &ad->port.ifs[0];
A
Alexander Graf 已提交
582

583
    sdb_fis->type = SATA_FIS_TYPE_SDB;
J
John Snow 已提交
584 585 586 587 588
    /* Interrupt pending & Notification bit */
    sdb_fis->flags = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
    sdb_fis->status = ide_state->status & 0x77;
    sdb_fis->error = ide_state->error;
    /* update SAct field in SDB_FIS */
A
Alexander Graf 已提交
589
    s->dev[port].finished |= finished;
J
John Snow 已提交
590
    sdb_fis->payload = cpu_to_le32(ad->finished);
A
Alexander Graf 已提交
591

592 593 594 595 596 597
    /* Update shadow registers (except BSY 0x80 and DRQ 0x08) */
    pr->tfdata = (ad->port.ifs[0].error << 8) |
        (ad->port.ifs[0].status & 0x77) |
        (pr->tfdata & 0x88);

    ahci_trigger_irq(s, ad, PORT_IRQ_SDB_FIS);
A
Alexander Graf 已提交
598 599
}

600 601 602 603 604 605
static void ahci_write_fis_pio(AHCIDevice *ad, uint16_t len)
{
    AHCIPortRegs *pr = &ad->port_regs;
    uint8_t *pio_fis, *cmd_fis;
    uint64_t tbl_addr;
    dma_addr_t cmd_len = 0x80;
J
John Snow 已提交
606
    IDEState *s = &ad->port.ifs[0];
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

    if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
        return;
    }

    /* map cmd_fis */
    tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
    cmd_fis = dma_memory_map(ad->hba->as, tbl_addr, &cmd_len,
                             DMA_DIRECTION_TO_DEVICE);

    if (cmd_fis == NULL) {
        DPRINTF(ad->port_no, "dma_memory_map failed in ahci_write_fis_pio");
        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR);
        return;
    }

    if (cmd_len != 0x80) {
        DPRINTF(ad->port_no,
                "dma_memory_map mapped too few bytes in ahci_write_fis_pio");
        dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
                         DMA_DIRECTION_TO_DEVICE, cmd_len);
        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR);
        return;
    }

    pio_fis = &ad->res_fis[RES_FIS_PSFIS];

634
    pio_fis[0] = SATA_FIS_TYPE_PIO_SETUP;
635
    pio_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
J
John Snow 已提交
636 637 638 639 640 641 642 643 644 645 646
    pio_fis[2] = s->status;
    pio_fis[3] = s->error;

    pio_fis[4] = s->sector;
    pio_fis[5] = s->lcyl;
    pio_fis[6] = s->hcyl;
    pio_fis[7] = s->select;
    pio_fis[8] = s->hob_sector;
    pio_fis[9] = s->hob_lcyl;
    pio_fis[10] = s->hob_hcyl;
    pio_fis[11] = 0;
647 648 649
    pio_fis[12] = cmd_fis[12];
    pio_fis[13] = cmd_fis[13];
    pio_fis[14] = 0;
J
John Snow 已提交
650
    pio_fis[15] = s->status;
651 652 653 654 655
    pio_fis[16] = len & 255;
    pio_fis[17] = len >> 8;
    pio_fis[18] = 0;
    pio_fis[19] = 0;

656 657 658 659
    /* Update shadow registers: */
    pr->tfdata = (ad->port.ifs[0].error << 8) |
        ad->port.ifs[0].status;

660 661 662 663 664 665 666 667 668 669
    if (pio_fis[2] & ERR_STAT) {
        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
    }

    ahci_trigger_irq(ad->hba, ad, PORT_IRQ_PIOS_FIS);

    dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
                     DMA_DIRECTION_TO_DEVICE, cmd_len);
}

A
Alexander Graf 已提交
670 671 672 673 674
static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
{
    AHCIPortRegs *pr = &ad->port_regs;
    uint8_t *d2h_fis;
    int i;
675
    dma_addr_t cmd_len = 0x80;
A
Alexander Graf 已提交
676
    int cmd_mapped = 0;
J
John Snow 已提交
677
    IDEState *s = &ad->port.ifs[0];
A
Alexander Graf 已提交
678 679 680 681 682 683 684 685

    if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
        return;
    }

    if (!cmd_fis) {
        /* map cmd_fis */
        uint64_t tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
P
Paolo Bonzini 已提交
686
        cmd_fis = dma_memory_map(ad->hba->as, tbl_addr, &cmd_len,
687
                                 DMA_DIRECTION_TO_DEVICE);
A
Alexander Graf 已提交
688 689 690 691 692
        cmd_mapped = 1;
    }

    d2h_fis = &ad->res_fis[RES_FIS_RFIS];

693
    d2h_fis[0] = SATA_FIS_TYPE_REGISTER_D2H;
A
Alexander Graf 已提交
694
    d2h_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
J
John Snow 已提交
695 696 697 698 699 700 701 702 703 704 705
    d2h_fis[2] = s->status;
    d2h_fis[3] = s->error;

    d2h_fis[4] = s->sector;
    d2h_fis[5] = s->lcyl;
    d2h_fis[6] = s->hcyl;
    d2h_fis[7] = s->select;
    d2h_fis[8] = s->hob_sector;
    d2h_fis[9] = s->hob_lcyl;
    d2h_fis[10] = s->hob_hcyl;
    d2h_fis[11] = 0;
A
Alexander Graf 已提交
706 707
    d2h_fis[12] = cmd_fis[12];
    d2h_fis[13] = cmd_fis[13];
708
    for (i = 14; i < 20; i++) {
A
Alexander Graf 已提交
709 710 711
        d2h_fis[i] = 0;
    }

712 713 714 715
    /* Update shadow registers: */
    pr->tfdata = (ad->port.ifs[0].error << 8) |
        ad->port.ifs[0].status;

A
Alexander Graf 已提交
716
    if (d2h_fis[2] & ERR_STAT) {
717
        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
A
Alexander Graf 已提交
718 719 720 721 722
    }

    ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS);

    if (cmd_mapped) {
P
Paolo Bonzini 已提交
723
        dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
724
                         DMA_DIRECTION_TO_DEVICE, cmd_len);
A
Alexander Graf 已提交
725 726 727
    }
}

728 729 730 731 732
static int prdt_tbl_entry_size(const AHCI_SG *tbl)
{
    return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1;
}

733 734
static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist,
                                int32_t offset)
A
Alexander Graf 已提交
735 736 737 738 739
{
    AHCICmdHdr *cmd = ad->cur_cmd;
    uint32_t opts = le32_to_cpu(cmd->opts);
    uint64_t prdt_addr = le64_to_cpu(cmd->tbl_addr) + 0x80;
    int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN;
740 741
    dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));
    dma_addr_t real_prdt_len = prdt_len;
A
Alexander Graf 已提交
742 743 744
    uint8_t *prdt;
    int i;
    int r = 0;
745
    uint64_t sum = 0;
746
    int off_idx = -1;
747
    int64_t off_pos = -1;
748
    int tbl_entry_size;
749 750
    IDEBus *bus = &ad->port;
    BusState *qbus = BUS(bus);
A
Alexander Graf 已提交
751

752 753 754 755 756 757 758 759
    /*
     * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support
     * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a
     * 512 byte sector size. We limit the PRDT in this implementation to
     * a reasonably large 2GiB, which can accommodate the maximum transfer
     * request for sector sizes up to 32K.
     */

A
Alexander Graf 已提交
760 761 762 763 764 765
    if (!sglist_alloc_hint) {
        DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);
        return -1;
    }

    /* map PRDT */
P
Paolo Bonzini 已提交
766
    if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,
767
                                DMA_DIRECTION_TO_DEVICE))){
A
Alexander Graf 已提交
768 769 770 771 772 773 774 775 776 777 778 779 780
        DPRINTF(ad->port_no, "map failed\n");
        return -1;
    }

    if (prdt_len < real_prdt_len) {
        DPRINTF(ad->port_no, "mapped less than expected\n");
        r = -1;
        goto out;
    }

    /* Get entries in the PRDT, init a qemu sglist accordingly */
    if (sglist_alloc_hint > 0) {
        AHCI_SG *tbl = (AHCI_SG *)prdt;
781
        sum = 0;
A
Alexander Graf 已提交
782
        for (i = 0; i < sglist_alloc_hint; i++) {
783
            /* flags_size is zero-based */
784
            tbl_entry_size = prdt_tbl_entry_size(&tbl[i]);
785 786 787 788 789 790 791 792 793
            if (offset <= (sum + tbl_entry_size)) {
                off_idx = i;
                off_pos = offset - sum;
                break;
            }
            sum += tbl_entry_size;
        }
        if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {
            DPRINTF(ad->port_no, "%s: Incorrect offset! "
794
                            "off_idx: %d, off_pos: %"PRId64"\n",
795 796 797 798 799
                            __func__, off_idx, off_pos);
            r = -1;
            goto out;
        }

800 801
        qemu_sglist_init(sglist, qbus->parent, (sglist_alloc_hint - off_idx),
                         ad->hba->as);
802
        qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr + off_pos),
803
                        prdt_tbl_entry_size(&tbl[off_idx]) - off_pos);
804 805

        for (i = off_idx + 1; i < sglist_alloc_hint; i++) {
A
Alexander Graf 已提交
806 807
            /* flags_size is zero-based */
            qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
808
                            prdt_tbl_entry_size(&tbl[i]));
809 810 811 812 813 814 815
            if (sglist->size > INT32_MAX) {
                error_report("AHCI Physical Region Descriptor Table describes "
                             "more than 2 GiB.\n");
                qemu_sglist_destroy(sglist);
                r = -1;
                goto out;
            }
A
Alexander Graf 已提交
816 817 818 819
        }
    }

out:
P
Paolo Bonzini 已提交
820
    dma_memory_unmap(ad->hba->as, prdt, prdt_len,
821
                     DMA_DIRECTION_TO_DEVICE, prdt_len);
A
Alexander Graf 已提交
822 823 824 825 826 827 828 829
    return r;
}

static void ncq_cb(void *opaque, int ret)
{
    NCQTransferState *ncq_tfs = (NCQTransferState *)opaque;
    IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];

830 831 832
    if (ret == -ECANCELED) {
        return;
    }
A
Alexander Graf 已提交
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    /* Clear bit for this tag in SActive */
    ncq_tfs->drive->port_regs.scr_act &= ~(1 << ncq_tfs->tag);

    if (ret < 0) {
        /* error */
        ide_state->error = ABRT_ERR;
        ide_state->status = READY_STAT | ERR_STAT;
        ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
    } else {
        ide_state->status = READY_STAT | SEEK_STAT;
    }

    ahci_write_fis_sdb(ncq_tfs->drive->hba, ncq_tfs->drive->port_no,
                       (1 << ncq_tfs->tag));

    DPRINTF(ncq_tfs->drive->port_no, "NCQ transfer tag %d finished\n",
            ncq_tfs->tag);

851
    block_acct_done(blk_get_stats(ncq_tfs->drive->port.ifs[0].blk),
852
                    &ncq_tfs->acct);
A
Alexander Graf 已提交
853 854 855 856
    qemu_sglist_destroy(&ncq_tfs->sglist);
    ncq_tfs->used = 0;
}

J
John Snow 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
static int is_ncq(uint8_t ata_cmd)
{
    /* Based on SATA 3.2 section 13.6.3.2 */
    switch (ata_cmd) {
    case READ_FPDMA_QUEUED:
    case WRITE_FPDMA_QUEUED:
    case NCQ_NON_DATA:
    case RECEIVE_FPDMA_QUEUED:
    case SEND_FPDMA_QUEUED:
        return 1;
    default:
        return 0;
    }
}

A
Alexander Graf 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
                                int slot)
{
    NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;
    uint8_t tag = ncq_fis->tag >> 3;
    NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[tag];

    if (ncq_tfs->used) {
        /* error - already in use */
        fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);
        return;
    }

    ncq_tfs->used = 1;
    ncq_tfs->drive = &s->dev[port];
    ncq_tfs->slot = slot;
    ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
                   ((uint64_t)ncq_fis->lba4 << 32) |
                   ((uint64_t)ncq_fis->lba3 << 24) |
                   ((uint64_t)ncq_fis->lba2 << 16) |
                   ((uint64_t)ncq_fis->lba1 << 8) |
                   (uint64_t)ncq_fis->lba0;

    /* Note: We calculate the sector count, but don't currently rely on it.
     * The total size of the DMA buffer tells us the transfer size instead. */
    ncq_tfs->sector_count = ((uint16_t)ncq_fis->sector_count_high << 8) |
                                ncq_fis->sector_count_low;

M
Max Filippov 已提交
900 901
    DPRINTF(port, "NCQ transfer LBA from %"PRId64" to %"PRId64", "
            "drive max %"PRId64"\n",
A
Alexander Graf 已提交
902 903 904
            ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 2,
            s->dev[port].port.ifs[0].nb_sectors - 1);

905
    ahci_populate_sglist(&s->dev[port], &ncq_tfs->sglist, 0);
A
Alexander Graf 已提交
906 907 908 909
    ncq_tfs->tag = tag;

    switch(ncq_fis->command) {
        case READ_FPDMA_QUEUED:
M
Max Filippov 已提交
910 911
            DPRINTF(port, "NCQ reading %d sectors from LBA %"PRId64", "
                    "tag %d\n",
A
Alexander Graf 已提交
912 913
                    ncq_tfs->sector_count-1, ncq_tfs->lba, ncq_tfs->tag);

M
Max Filippov 已提交
914 915
            DPRINTF(port, "tag %d aio read %"PRId64"\n",
                    ncq_tfs->tag, ncq_tfs->lba);
916

917
            dma_acct_start(ncq_tfs->drive->port.ifs[0].blk, &ncq_tfs->acct,
918
                           &ncq_tfs->sglist, BLOCK_ACCT_READ);
919 920 921
            ncq_tfs->aiocb = dma_blk_read(ncq_tfs->drive->port.ifs[0].blk,
                                          &ncq_tfs->sglist, ncq_tfs->lba,
                                          ncq_cb, ncq_tfs);
A
Alexander Graf 已提交
922 923
            break;
        case WRITE_FPDMA_QUEUED:
M
Max Filippov 已提交
924
            DPRINTF(port, "NCQ writing %d sectors to LBA %"PRId64", tag %d\n",
A
Alexander Graf 已提交
925 926
                    ncq_tfs->sector_count-1, ncq_tfs->lba, ncq_tfs->tag);

M
Max Filippov 已提交
927 928
            DPRINTF(port, "tag %d aio write %"PRId64"\n",
                    ncq_tfs->tag, ncq_tfs->lba);
929

930
            dma_acct_start(ncq_tfs->drive->port.ifs[0].blk, &ncq_tfs->acct,
931
                           &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
932 933 934
            ncq_tfs->aiocb = dma_blk_write(ncq_tfs->drive->port.ifs[0].blk,
                                           &ncq_tfs->sglist, ncq_tfs->lba,
                                           ncq_cb, ncq_tfs);
A
Alexander Graf 已提交
935 936
            break;
        default:
J
John Snow 已提交
937 938 939 940 941 942 943 944
            if (is_ncq(cmd_fis[2])) {
                DPRINTF(port,
                        "error: unsupported NCQ command (0x%02x) received\n",
                        cmd_fis[2]);
            } else {
                DPRINTF(port,
                        "error: tried to process non-NCQ command as NCQ\n");
            }
A
Alexander Graf 已提交
945 946 947 948
            qemu_sglist_destroy(&ncq_tfs->sglist);
    }
}

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
static void handle_reg_h2d_fis(AHCIState *s, int port,
                               int slot, uint8_t *cmd_fis)
{
    IDEState *ide_state = &s->dev[port].port.ifs[0];
    AHCICmdHdr *cmd = s->dev[port].cur_cmd;
    uint32_t opts = le32_to_cpu(cmd->opts);

    if (cmd_fis[1] & 0x0F) {
        DPRINTF(port, "Port Multiplier not supported."
                " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
                cmd_fis[0], cmd_fis[1], cmd_fis[2]);
        return;
    }

    if (cmd_fis[1] & 0x70) {
        DPRINTF(port, "Reserved flags set in H2D Register FIS."
                " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
                cmd_fis[0], cmd_fis[1], cmd_fis[2]);
        return;
    }

    if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {
        switch (s->dev[port].port_state) {
        case STATE_RUN:
            if (cmd_fis[15] & ATA_SRST) {
                s->dev[port].port_state = STATE_RESET;
            }
            break;
        case STATE_RESET:
            if (!(cmd_fis[15] & ATA_SRST)) {
                ahci_reset_port(s, port);
            }
            break;
        }
        return;
    }

    /* Check for NCQ command */
    if (is_ncq(cmd_fis[2])) {
        process_ncq_command(s, port, cmd_fis, slot);
        return;
    }

    /* Decompose the FIS:
     * AHCI does not interpret FIS packets, it only forwards them.
     * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.
     * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.
     *
     * ATA4 describes sector number for LBA28/CHS commands.
     * ATA6 describes sector number for LBA48 commands.
     * ATA8 deprecates CHS fully, describing only LBA28/48.
     *
     * We dutifully convert the FIS into IDE registers, and allow the
     * core layer to interpret them as needed. */
    ide_state->feature = cmd_fis[3];
    ide_state->sector = cmd_fis[4];      /* LBA 7:0 */
    ide_state->lcyl = cmd_fis[5];        /* LBA 15:8  */
    ide_state->hcyl = cmd_fis[6];        /* LBA 23:16 */
    ide_state->select = cmd_fis[7];      /* LBA 27:24 (LBA28) */
    ide_state->hob_sector = cmd_fis[8];  /* LBA 31:24 */
    ide_state->hob_lcyl = cmd_fis[9];    /* LBA 39:32 */
    ide_state->hob_hcyl = cmd_fis[10];   /* LBA 47:40 */
    ide_state->hob_feature = cmd_fis[11];
    ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
    /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */
    /* 15: Only valid when UPDATE_COMMAND not set. */

    /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
     * table to ide_state->io_buffer */
    if (opts & AHCI_CMD_ATAPI) {
        memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
        debug_print_fis(ide_state->io_buffer, 0x10);
        s->dev[port].done_atapi_packet = false;
        /* XXX send PIO setup FIS */
    }

    ide_state->error = 0;

    /* Reset transferred byte counter */
    cmd->status = 0;

    /* We're ready to process the command in FIS byte 2. */
    ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);
}

A
Alexander Graf 已提交
1034 1035 1036 1037 1038 1039
static int handle_cmd(AHCIState *s, int port, int slot)
{
    IDEState *ide_state;
    uint64_t tbl_addr;
    AHCICmdHdr *cmd;
    uint8_t *cmd_fis;
1040
    dma_addr_t cmd_len;
A
Alexander Graf 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
        /* Engine currently busy, try again later */
        DPRINTF(port, "engine busy\n");
        return -1;
    }

    if (!s->dev[port].lst) {
        DPRINTF(port, "error: lst not given but cmd handled");
        return -1;
    }
1052
    cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];
A
Alexander Graf 已提交
1053 1054 1055
    /* remember current slot handle for later */
    s->dev[port].cur_cmd = cmd;

1056 1057 1058 1059 1060 1061 1062
    /* The device we are working for */
    ide_state = &s->dev[port].port.ifs[0];
    if (!ide_state->blk) {
        DPRINTF(port, "error: guest accessed unused port");
        return -1;
    }

A
Alexander Graf 已提交
1063 1064
    tbl_addr = le64_to_cpu(cmd->tbl_addr);
    cmd_len = 0x80;
P
Paolo Bonzini 已提交
1065
    cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,
1066
                             DMA_DIRECTION_FROM_DEVICE);
A
Alexander Graf 已提交
1067 1068 1069
    if (!cmd_fis) {
        DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
        return -1;
1070 1071 1072 1073 1074
    } else if (cmd_len != 0x80) {
        ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR);
        DPRINTF(port, "error: dma_memory_map failed: "
                "(len(%02"PRIx64") != 0x80)\n",
                cmd_len);
A
Alexander Graf 已提交
1075 1076
        goto out;
    }
1077
    debug_print_fis(cmd_fis, 0x80);
A
Alexander Graf 已提交
1078 1079 1080

    switch (cmd_fis[0]) {
        case SATA_FIS_TYPE_REGISTER_H2D:
1081
            handle_reg_h2d_fis(s, port, slot, cmd_fis);
A
Alexander Graf 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090
            break;
        default:
            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
                          cmd_fis[2]);
            break;
    }

out:
P
Paolo Bonzini 已提交
1091
    dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,
1092
                     cmd_len);
A
Alexander Graf 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
        /* async command, complete later */
        s->dev[port].busy_slot = slot;
        return -1;
    }

    /* done handling the command */
    return 0;
}

/* DMA dev <-> ram */
1105
static void ahci_start_transfer(IDEDMA *dma)
A
Alexander Graf 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
    IDEState *s = &ad->port.ifs[0];
    uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
    /* write == ram -> device */
    uint32_t opts = le32_to_cpu(ad->cur_cmd->opts);
    int is_write = opts & AHCI_CMD_WRITE;
    int is_atapi = opts & AHCI_CMD_ATAPI;
    int has_sglist = 0;

    if (is_atapi && !ad->done_atapi_packet) {
        /* already prepopulated iobuffer */
1118
        ad->done_atapi_packet = true;
1119
        size = 0;
A
Alexander Graf 已提交
1120 1121 1122
        goto out;
    }

J
John Snow 已提交
1123
    if (ahci_dma_prepare_buf(dma, is_write)) {
A
Alexander Graf 已提交
1124 1125 1126 1127 1128 1129 1130
        has_sglist = 1;
    }

    DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",
            is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",
            has_sglist ? "" : "o");

P
Paolo Bonzini 已提交
1131 1132 1133 1134 1135 1136
    if (has_sglist && size) {
        if (is_write) {
            dma_buf_write(s->data_ptr, size, &s->sg);
        } else {
            dma_buf_read(s->data_ptr, size, &s->sg);
        }
A
Alexander Graf 已提交
1137 1138 1139 1140 1141 1142
    }

out:
    /* declare that we processed everything */
    s->data_ptr = s->data_end;

1143 1144
    /* Update number of transferred bytes, destroy sglist */
    ahci_commit_buf(dma, size);
A
Alexander Graf 已提交
1145 1146

    s->end_transfer_func(s);
1147 1148 1149 1150 1151

    if (!(s->status & DRQ_STAT)) {
        /* done with PIO send/receive */
        ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));
    }
A
Alexander Graf 已提交
1152 1153 1154
}

static void ahci_start_dma(IDEDMA *dma, IDEState *s,
1155
                           BlockCompletionFunc *dma_cb)
A
Alexander Graf 已提交
1156 1157 1158
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
    DPRINTF(ad->port_no, "\n");
1159
    s->io_buffer_offset = 0;
A
Alexander Graf 已提交
1160 1161 1162
    dma_cb(s, 0);
}

1163 1164 1165 1166 1167
/**
 * Called in DMA R/W chains to read the PRDT, utilizing ahci_populate_sglist.
 * Not currently invoked by PIO R/W chains,
 * which invoke ahci_populate_sglist via ahci_start_transfer.
 */
1168
static int32_t ahci_dma_prepare_buf(IDEDMA *dma, int is_write)
A
Alexander Graf 已提交
1169 1170 1171 1172
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
    IDEState *s = &ad->port.ifs[0];

1173 1174 1175 1176
    if (ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset) == -1) {
        DPRINTF(ad->port_no, "ahci_dma_prepare_buf failed.\n");
        return -1;
    }
P
Paolo Bonzini 已提交
1177
    s->io_buffer_size = s->sg.size;
A
Alexander Graf 已提交
1178 1179

    DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
1180
    return s->io_buffer_size;
A
Alexander Graf 已提交
1181 1182
}

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
/**
 * Destroys the scatter-gather list,
 * and updates the command header with a bytes-read value.
 * called explicitly via ahci_dma_rw_buf (ATAPI DMA),
 * and ahci_start_transfer (PIO R/W),
 * and called via callback from ide_dma_cb for DMA R/W paths.
 */
static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes)
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
    IDEState *s = &ad->port.ifs[0];

    tx_bytes += le32_to_cpu(ad->cur_cmd->status);
    ad->cur_cmd->status = cpu_to_le32(tx_bytes);

    qemu_sglist_destroy(&s->sg);
}

A
Alexander Graf 已提交
1201 1202 1203 1204 1205 1206 1207
static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
    IDEState *s = &ad->port.ifs[0];
    uint8_t *p = s->io_buffer + s->io_buffer_index;
    int l = s->io_buffer_size - s->io_buffer_index;

1208
    if (ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset)) {
A
Alexander Graf 已提交
1209 1210 1211 1212
        return 0;
    }

    if (is_write) {
P
Paolo Bonzini 已提交
1213
        dma_buf_read(p, l, &s->sg);
A
Alexander Graf 已提交
1214
    } else {
P
Paolo Bonzini 已提交
1215
        dma_buf_write(p, l, &s->sg);
A
Alexander Graf 已提交
1216 1217
    }

1218 1219
    /* free sglist, update byte count */
    ahci_commit_buf(dma, l);
1220

A
Alexander Graf 已提交
1221
    s->io_buffer_index += l;
1222
    s->io_buffer_offset += l;
A
Alexander Graf 已提交
1223 1224 1225 1226 1227 1228

    DPRINTF(ad->port_no, "len=%#x\n", l);

    return 1;
}

1229
static void ahci_cmd_done(IDEDMA *dma)
A
Alexander Graf 已提交
1230 1231 1232
{
    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

1233
    DPRINTF(ad->port_no, "cmd done\n");
A
Alexander Graf 已提交
1234 1235 1236 1237

    /* update d2h status */
    ahci_write_fis_d2h(ad, NULL);

1238 1239 1240 1241 1242
    if (!ad->check_bh) {
        /* maybe we still have something to process, check later */
        ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad);
        qemu_bh_schedule(ad->check_bh);
    }
A
Alexander Graf 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
}

static void ahci_irq_set(void *opaque, int n, int level)
{
}

static const IDEDMAOps ahci_dma_ops = {
    .start_dma = ahci_start_dma,
    .start_transfer = ahci_start_transfer,
    .prepare_buf = ahci_dma_prepare_buf,
1253
    .commit_buf = ahci_commit_buf,
A
Alexander Graf 已提交
1254
    .rw_buf = ahci_dma_rw_buf,
1255
    .cmd_done = ahci_cmd_done,
A
Alexander Graf 已提交
1256 1257
};

P
Paolo Bonzini 已提交
1258
void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports)
A
Alexander Graf 已提交
1259 1260 1261 1262
{
    qemu_irq *irqs;
    int i;

P
Paolo Bonzini 已提交
1263
    s->as = as;
1264
    s->ports = ports;
1265
    s->dev = g_new0(AHCIDevice, ports);
A
Alexander Graf 已提交
1266
    ahci_reg_init(s);
A
Avi Kivity 已提交
1267
    /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1268 1269 1270 1271
    memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s,
                          "ahci", AHCI_MEM_BAR_SIZE);
    memory_region_init_io(&s->idp, OBJECT(qdev), &ahci_idp_ops, s,
                          "ahci-idp", 32);
1272

1273
    irqs = qemu_allocate_irqs(ahci_irq_set, s, s->ports);
A
Alexander Graf 已提交
1274

1275
    for (i = 0; i < s->ports; i++) {
A
Alexander Graf 已提交
1276 1277
        AHCIDevice *ad = &s->dev[i];

1278
        ide_bus_new(&ad->port, sizeof(ad->port), qdev, i, 1);
A
Alexander Graf 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287
        ide_init2(&ad->port, irqs[i]);

        ad->hba = s;
        ad->port_no = i;
        ad->port.dma = &ad->dma;
        ad->port.dma->ops = &ahci_dma_ops;
    }
}

1288 1289
void ahci_uninit(AHCIState *s)
{
1290
    g_free(s->dev);
1291 1292
}

J
Jan Kiszka 已提交
1293
void ahci_reset(AHCIState *s)
A
Alexander Graf 已提交
1294
{
1295
    AHCIPortRegs *pr;
A
Alexander Graf 已提交
1296 1297
    int i;

J
Jan Kiszka 已提交
1298
    s->control_regs.irqstatus = 0;
M
Michael S. Tsirkin 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307
    /* AHCI Enable (AE)
     * The implementation of this bit is dependent upon the value of the
     * CAP.SAM bit. If CAP.SAM is '0', then GHC.AE shall be read-write and
     * shall have a reset value of '0'. If CAP.SAM is '1', then AE shall be
     * read-only and shall have a reset value of '1'.
     *
     * We set HOST_CAP_AHCI so we must enable AHCI at reset.
     */
    s->control_regs.ghc = HOST_CTL_AHCI_EN;
A
Alexander Graf 已提交
1308

J
Jan Kiszka 已提交
1309 1310
    for (i = 0; i < s->ports; i++) {
        pr = &s->dev[i].port_regs;
1311 1312 1313
        pr->irq_stat = 0;
        pr->irq_mask = 0;
        pr->scr_ctl = 0;
1314
        pr->cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
J
Jan Kiszka 已提交
1315
        ahci_reset_port(s, i);
A
Alexander Graf 已提交
1316 1317
    }
}
1318

J
Jason Baron 已提交
1319 1320 1321
static const VMStateDescription vmstate_ahci_device = {
    .name = "ahci port",
    .version_id = 1,
1322
    .fields = (VMStateField[]) {
J
Jason Baron 已提交
1323
        VMSTATE_IDE_BUS(port, AHCIDevice),
J
John Snow 已提交
1324
        VMSTATE_IDE_DRIVE(port.ifs[0], AHCIDevice),
J
Jason Baron 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        VMSTATE_UINT32(port_state, AHCIDevice),
        VMSTATE_UINT32(finished, AHCIDevice),
        VMSTATE_UINT32(port_regs.lst_addr, AHCIDevice),
        VMSTATE_UINT32(port_regs.lst_addr_hi, AHCIDevice),
        VMSTATE_UINT32(port_regs.fis_addr, AHCIDevice),
        VMSTATE_UINT32(port_regs.fis_addr_hi, AHCIDevice),
        VMSTATE_UINT32(port_regs.irq_stat, AHCIDevice),
        VMSTATE_UINT32(port_regs.irq_mask, AHCIDevice),
        VMSTATE_UINT32(port_regs.cmd, AHCIDevice),
        VMSTATE_UINT32(port_regs.tfdata, AHCIDevice),
        VMSTATE_UINT32(port_regs.sig, AHCIDevice),
        VMSTATE_UINT32(port_regs.scr_stat, AHCIDevice),
        VMSTATE_UINT32(port_regs.scr_ctl, AHCIDevice),
        VMSTATE_UINT32(port_regs.scr_err, AHCIDevice),
        VMSTATE_UINT32(port_regs.scr_act, AHCIDevice),
        VMSTATE_UINT32(port_regs.cmd_issue, AHCIDevice),
        VMSTATE_BOOL(done_atapi_packet, AHCIDevice),
        VMSTATE_INT32(busy_slot, AHCIDevice),
        VMSTATE_BOOL(init_d2h_sent, AHCIDevice),
        VMSTATE_END_OF_LIST()
    },
};

static int ahci_state_post_load(void *opaque, int version_id)
{
    int i;
    struct AHCIDevice *ad;
    AHCIState *s = opaque;

    for (i = 0; i < s->ports; i++) {
        ad = &s->dev[i];
        AHCIPortRegs *pr = &ad->port_regs;

1358
        map_page(s->as, &ad->lst,
J
Jason Baron 已提交
1359
                 ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
1360
        map_page(s->as, &ad->res_fis,
J
Jason Baron 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
                 ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
        /*
         * All pending i/o should be flushed out on a migrate. However,
         * we might not have cleared the busy_slot since this is done
         * in a bh. Also, issue i/o against any slots that are pending.
         */
        if ((ad->busy_slot != -1) &&
            !(ad->port.ifs[0].status & (BUSY_STAT|DRQ_STAT))) {
            pr->cmd_issue &= ~(1 << ad->busy_slot);
            ad->busy_slot = -1;
        }
        check_cmd(s, i);
    }

    return 0;
}

const VMStateDescription vmstate_ahci = {
    .name = "ahci",
    .version_id = 1,
    .post_load = ahci_state_post_load,
1382
    .fields = (VMStateField[]) {
J
Jason Baron 已提交
1383 1384 1385 1386 1387 1388 1389 1390
        VMSTATE_STRUCT_VARRAY_POINTER_INT32(dev, AHCIState, ports,
                                     vmstate_ahci_device, AHCIDevice),
        VMSTATE_UINT32(control_regs.cap, AHCIState),
        VMSTATE_UINT32(control_regs.ghc, AHCIState),
        VMSTATE_UINT32(control_regs.irqstatus, AHCIState),
        VMSTATE_UINT32(control_regs.impl, AHCIState),
        VMSTATE_UINT32(control_regs.version, AHCIState),
        VMSTATE_UINT32(idp_index, AHCIState),
1391
        VMSTATE_INT32_EQUAL(ports, AHCIState),
J
Jason Baron 已提交
1392 1393 1394 1395
        VMSTATE_END_OF_LIST()
    },
};

H
Hu Tao 已提交
1396 1397 1398
#define TYPE_SYSBUS_AHCI "sysbus-ahci"
#define SYSBUS_AHCI(obj) OBJECT_CHECK(SysbusAHCIState, (obj), TYPE_SYSBUS_AHCI)

1399
typedef struct SysbusAHCIState {
H
Hu Tao 已提交
1400 1401 1402 1403
    /*< private >*/
    SysBusDevice parent_obj;
    /*< public >*/

1404 1405 1406 1407 1408 1409
    AHCIState ahci;
    uint32_t num_ports;
} SysbusAHCIState;

static const VMStateDescription vmstate_sysbus_ahci = {
    .name = "sysbus-ahci",
J
Jason Baron 已提交
1410
    .unmigratable = 1, /* Still buggy under I/O load */
1411
    .fields = (VMStateField[]) {
R
Rob Herring 已提交
1412
        VMSTATE_AHCI(ahci, SysbusAHCIState),
J
Jason Baron 已提交
1413 1414
        VMSTATE_END_OF_LIST()
    },
1415 1416
};

J
Jan Kiszka 已提交
1417 1418
static void sysbus_ahci_reset(DeviceState *dev)
{
H
Hu Tao 已提交
1419
    SysbusAHCIState *s = SYSBUS_AHCI(dev);
J
Jan Kiszka 已提交
1420 1421 1422 1423

    ahci_reset(&s->ahci);
}

H
Hu Tao 已提交
1424
static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
1425
{
H
Hu Tao 已提交
1426
    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
H
Hu Tao 已提交
1427
    SysbusAHCIState *s = SYSBUS_AHCI(dev);
1428

R
Rob Herring 已提交
1429
    ahci_init(&s->ahci, dev, &address_space_memory, s->num_ports);
H
Hu Tao 已提交
1430 1431 1432

    sysbus_init_mmio(sbd, &s->ahci.mem);
    sysbus_init_irq(sbd, &s->ahci.irq);
1433 1434
}

1435 1436 1437 1438 1439
static Property sysbus_ahci_properties[] = {
    DEFINE_PROP_UINT32("num-ports", SysbusAHCIState, num_ports, 1),
    DEFINE_PROP_END_OF_LIST(),
};

1440 1441
static void sysbus_ahci_class_init(ObjectClass *klass, void *data)
{
1442
    DeviceClass *dc = DEVICE_CLASS(klass);
1443

H
Hu Tao 已提交
1444
    dc->realize = sysbus_ahci_realize;
1445 1446
    dc->vmsd = &vmstate_sysbus_ahci;
    dc->props = sysbus_ahci_properties;
J
Jan Kiszka 已提交
1447
    dc->reset = sysbus_ahci_reset;
1448
    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1449 1450
}

1451
static const TypeInfo sysbus_ahci_info = {
H
Hu Tao 已提交
1452
    .name          = TYPE_SYSBUS_AHCI,
1453 1454 1455
    .parent        = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(SysbusAHCIState),
    .class_init    = sysbus_ahci_class_init,
1456 1457
};

A
Andreas Färber 已提交
1458
static void sysbus_ahci_register_types(void)
1459
{
1460
    type_register_static(&sysbus_ahci_info);
1461 1462
}

A
Andreas Färber 已提交
1463
type_init(sysbus_ahci_register_types)
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd)
{
    AHCIPCIState *d = ICH_AHCI(dev);
    AHCIState *ahci = &d->ahci;
    int i;

    for (i = 0; i < ahci->ports; i++) {
        if (hd[i] == NULL) {
            continue;
        }
        ide_create_drive(&ahci->dev[i].port, 0, hd[i]);
    }

}