qemu/tests/ide-test.c
<<
>>
Prefs
   1/*
   2 * IDE test cases
   3 *
   4 * Copyright (c) 2013 Kevin Wolf <kwolf@redhat.com>
   5 *
   6 * Permission is hereby granted, free of charge, to any person obtaining a copy
   7 * of this software and associated documentation files (the "Software"), to deal
   8 * in the Software without restriction, including without limitation the rights
   9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10 * copies of the Software, and to permit persons to whom the Software is
  11 * furnished to do so, subject to the following conditions:
  12 *
  13 * The above copyright notice and this permission notice shall be included in
  14 * all copies or substantial portions of the Software.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22 * THE SOFTWARE.
  23 */
  24
  25#include "qemu/osdep.h"
  26
  27
  28#include "libqtest.h"
  29#include "libqos/libqos.h"
  30#include "libqos/pci-pc.h"
  31#include "libqos/malloc-pc.h"
  32
  33#include "qemu-common.h"
  34#include "qemu/bswap.h"
  35#include "hw/pci/pci_ids.h"
  36#include "hw/pci/pci_regs.h"
  37
  38#define TEST_IMAGE_SIZE 64 * 1024 * 1024
  39
  40#define IDE_PCI_DEV     1
  41#define IDE_PCI_FUNC    1
  42
  43#define IDE_BASE 0x1f0
  44#define IDE_PRIMARY_IRQ 14
  45
  46#define ATAPI_BLOCK_SIZE 2048
  47
  48/* How many bytes to receive via ATAPI PIO at one time.
  49 * Must be less than 0xFFFF. */
  50#define BYTE_COUNT_LIMIT 5120
  51
  52enum {
  53    reg_data        = 0x0,
  54    reg_feature     = 0x1,
  55    reg_nsectors    = 0x2,
  56    reg_lba_low     = 0x3,
  57    reg_lba_middle  = 0x4,
  58    reg_lba_high    = 0x5,
  59    reg_device      = 0x6,
  60    reg_status      = 0x7,
  61    reg_command     = 0x7,
  62};
  63
  64enum {
  65    BSY     = 0x80,
  66    DRDY    = 0x40,
  67    DF      = 0x20,
  68    DRQ     = 0x08,
  69    ERR     = 0x01,
  70};
  71
  72enum {
  73    DEV     = 0x10,
  74    LBA     = 0x40,
  75};
  76
  77enum {
  78    bmreg_cmd       = 0x0,
  79    bmreg_status    = 0x2,
  80    bmreg_prdt      = 0x4,
  81};
  82
  83enum {
  84    CMD_READ_DMA    = 0xc8,
  85    CMD_WRITE_DMA   = 0xca,
  86    CMD_FLUSH_CACHE = 0xe7,
  87    CMD_IDENTIFY    = 0xec,
  88    CMD_PACKET      = 0xa0,
  89
  90    CMDF_ABORT      = 0x100,
  91    CMDF_NO_BM      = 0x200,
  92};
  93
  94enum {
  95    BM_CMD_START    =  0x1,
  96    BM_CMD_WRITE    =  0x8, /* write = from device to memory */
  97};
  98
  99enum {
 100    BM_STS_ACTIVE   =  0x1,
 101    BM_STS_ERROR    =  0x2,
 102    BM_STS_INTR     =  0x4,
 103};
 104
 105enum {
 106    PRDT_EOT        = 0x80000000,
 107};
 108
 109#define assert_bit_set(data, mask) g_assert_cmphex((data) & (mask), ==, (mask))
 110#define assert_bit_clear(data, mask) g_assert_cmphex((data) & (mask), ==, 0)
 111
 112static QPCIBus *pcibus = NULL;
 113static QGuestAllocator *guest_malloc;
 114
 115static char tmp_path[] = "/tmp/qtest.XXXXXX";
 116static char debug_path[] = "/tmp/qtest-blkdebug.XXXXXX";
 117
 118static void ide_test_start(const char *cmdline_fmt, ...)
 119{
 120    va_list ap;
 121    char *cmdline;
 122
 123    va_start(ap, cmdline_fmt);
 124    cmdline = g_strdup_vprintf(cmdline_fmt, ap);
 125    va_end(ap);
 126
 127    qtest_start(cmdline);
 128    guest_malloc = pc_alloc_init();
 129
 130    g_free(cmdline);
 131}
 132
 133static void ide_test_quit(void)
 134{
 135    pc_alloc_uninit(guest_malloc);
 136    guest_malloc = NULL;
 137    qtest_end();
 138}
 139
 140static QPCIDevice *get_pci_device(QPCIBar *bmdma_bar, QPCIBar *ide_bar)
 141{
 142    QPCIDevice *dev;
 143    uint16_t vendor_id, device_id;
 144
 145    if (!pcibus) {
 146        pcibus = qpci_init_pc(NULL);
 147    }
 148
 149    /* Find PCI device and verify it's the right one */
 150    dev = qpci_device_find(pcibus, QPCI_DEVFN(IDE_PCI_DEV, IDE_PCI_FUNC));
 151    g_assert(dev != NULL);
 152
 153    vendor_id = qpci_config_readw(dev, PCI_VENDOR_ID);
 154    device_id = qpci_config_readw(dev, PCI_DEVICE_ID);
 155    g_assert(vendor_id == PCI_VENDOR_ID_INTEL);
 156    g_assert(device_id == PCI_DEVICE_ID_INTEL_82371SB_1);
 157
 158    /* Map bmdma BAR */
 159    *bmdma_bar = qpci_iomap(dev, 4, NULL);
 160
 161    *ide_bar = qpci_legacy_iomap(dev, IDE_BASE);
 162
 163    qpci_device_enable(dev);
 164
 165    return dev;
 166}
 167
 168static void free_pci_device(QPCIDevice *dev)
 169{
 170    /* libqos doesn't have a function for this, so free it manually */
 171    g_free(dev);
 172}
 173
 174typedef struct PrdtEntry {
 175    uint32_t addr;
 176    uint32_t size;
 177} QEMU_PACKED PrdtEntry;
 178
 179#define assert_bit_set(data, mask) g_assert_cmphex((data) & (mask), ==, (mask))
 180#define assert_bit_clear(data, mask) g_assert_cmphex((data) & (mask), ==, 0)
 181
 182static int send_dma_request(int cmd, uint64_t sector, int nb_sectors,
 183                            PrdtEntry *prdt, int prdt_entries,
 184                            void(*post_exec)(QPCIDevice *dev, QPCIBar ide_bar,
 185                                             uint64_t sector, int nb_sectors))
 186{
 187    QPCIDevice *dev;
 188    QPCIBar bmdma_bar, ide_bar;
 189    uintptr_t guest_prdt;
 190    size_t len;
 191    bool from_dev;
 192    uint8_t status;
 193    int flags;
 194
 195    dev = get_pci_device(&bmdma_bar, &ide_bar);
 196
 197    flags = cmd & ~0xff;
 198    cmd &= 0xff;
 199
 200    switch (cmd) {
 201    case CMD_READ_DMA:
 202    case CMD_PACKET:
 203        /* Assuming we only test data reads w/ ATAPI, otherwise we need to know
 204         * the SCSI command being sent in the packet, too. */
 205        from_dev = true;
 206        break;
 207    case CMD_WRITE_DMA:
 208        from_dev = false;
 209        break;
 210    default:
 211        g_assert_not_reached();
 212    }
 213
 214    if (flags & CMDF_NO_BM) {
 215        qpci_config_writew(dev, PCI_COMMAND,
 216                           PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
 217    }
 218
 219    /* Select device 0 */
 220    qpci_io_writeb(dev, ide_bar, reg_device, 0 | LBA);
 221
 222    /* Stop any running transfer, clear any pending interrupt */
 223    qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 224    qpci_io_writeb(dev, bmdma_bar, bmreg_status, BM_STS_INTR);
 225
 226    /* Setup PRDT */
 227    len = sizeof(*prdt) * prdt_entries;
 228    guest_prdt = guest_alloc(guest_malloc, len);
 229    memwrite(guest_prdt, prdt, len);
 230    qpci_io_writel(dev, bmdma_bar, bmreg_prdt, guest_prdt);
 231
 232    /* ATA DMA command */
 233    if (cmd == CMD_PACKET) {
 234        /* Enables ATAPI DMA; otherwise PIO is attempted */
 235        qpci_io_writeb(dev, ide_bar, reg_feature, 0x01);
 236    } else {
 237        qpci_io_writeb(dev, ide_bar, reg_nsectors, nb_sectors);
 238        qpci_io_writeb(dev, ide_bar, reg_lba_low,    sector & 0xff);
 239        qpci_io_writeb(dev, ide_bar, reg_lba_middle, (sector >> 8) & 0xff);
 240        qpci_io_writeb(dev, ide_bar, reg_lba_high,   (sector >> 16) & 0xff);
 241    }
 242
 243    qpci_io_writeb(dev, ide_bar, reg_command, cmd);
 244
 245    if (post_exec) {
 246        post_exec(dev, ide_bar, sector, nb_sectors);
 247    }
 248
 249    /* Start DMA transfer */
 250    qpci_io_writeb(dev, bmdma_bar, bmreg_cmd,
 251                   BM_CMD_START | (from_dev ? BM_CMD_WRITE : 0));
 252
 253    if (flags & CMDF_ABORT) {
 254        qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 255    }
 256
 257    /* Wait for the DMA transfer to complete */
 258    do {
 259        status = qpci_io_readb(dev, bmdma_bar, bmreg_status);
 260    } while ((status & (BM_STS_ACTIVE | BM_STS_INTR)) == BM_STS_ACTIVE);
 261
 262    g_assert_cmpint(get_irq(IDE_PRIMARY_IRQ), ==, !!(status & BM_STS_INTR));
 263
 264    /* Check IDE status code */
 265    assert_bit_set(qpci_io_readb(dev, ide_bar, reg_status), DRDY);
 266    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), BSY | DRQ);
 267
 268    /* Reading the status register clears the IRQ */
 269    g_assert(!get_irq(IDE_PRIMARY_IRQ));
 270
 271    /* Stop DMA transfer if still active */
 272    if (status & BM_STS_ACTIVE) {
 273        qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 274    }
 275
 276    free_pci_device(dev);
 277
 278    return status;
 279}
 280
 281static void test_bmdma_simple_rw(void)
 282{
 283    QPCIDevice *dev;
 284    QPCIBar bmdma_bar, ide_bar;
 285    uint8_t status;
 286    uint8_t *buf;
 287    uint8_t *cmpbuf;
 288    size_t len = 512;
 289    uintptr_t guest_buf = guest_alloc(guest_malloc, len);
 290
 291    PrdtEntry prdt[] = {
 292        {
 293            .addr = cpu_to_le32(guest_buf),
 294            .size = cpu_to_le32(len | PRDT_EOT),
 295        },
 296    };
 297
 298    dev = get_pci_device(&bmdma_bar, &ide_bar);
 299
 300    buf = g_malloc(len);
 301    cmpbuf = g_malloc(len);
 302
 303    /* Write 0x55 pattern to sector 0 */
 304    memset(buf, 0x55, len);
 305    memwrite(guest_buf, buf, len);
 306
 307    status = send_dma_request(CMD_WRITE_DMA, 0, 1, prdt,
 308                              ARRAY_SIZE(prdt), NULL);
 309    g_assert_cmphex(status, ==, BM_STS_INTR);
 310    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 311
 312    /* Write 0xaa pattern to sector 1 */
 313    memset(buf, 0xaa, len);
 314    memwrite(guest_buf, buf, len);
 315
 316    status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt,
 317                              ARRAY_SIZE(prdt), NULL);
 318    g_assert_cmphex(status, ==, BM_STS_INTR);
 319    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 320
 321    /* Read and verify 0x55 pattern in sector 0 */
 322    memset(cmpbuf, 0x55, len);
 323
 324    status = send_dma_request(CMD_READ_DMA, 0, 1, prdt, ARRAY_SIZE(prdt), NULL);
 325    g_assert_cmphex(status, ==, BM_STS_INTR);
 326    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 327
 328    memread(guest_buf, buf, len);
 329    g_assert(memcmp(buf, cmpbuf, len) == 0);
 330
 331    /* Read and verify 0xaa pattern in sector 1 */
 332    memset(cmpbuf, 0xaa, len);
 333
 334    status = send_dma_request(CMD_READ_DMA, 1, 1, prdt, ARRAY_SIZE(prdt), NULL);
 335    g_assert_cmphex(status, ==, BM_STS_INTR);
 336    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 337
 338    memread(guest_buf, buf, len);
 339    g_assert(memcmp(buf, cmpbuf, len) == 0);
 340
 341
 342    g_free(buf);
 343    g_free(cmpbuf);
 344}
 345
 346static void test_bmdma_short_prdt(void)
 347{
 348    QPCIDevice *dev;
 349    QPCIBar bmdma_bar, ide_bar;
 350    uint8_t status;
 351
 352    PrdtEntry prdt[] = {
 353        {
 354            .addr = 0,
 355            .size = cpu_to_le32(0x10 | PRDT_EOT),
 356        },
 357    };
 358
 359    dev = get_pci_device(&bmdma_bar, &ide_bar);
 360
 361    /* Normal request */
 362    status = send_dma_request(CMD_READ_DMA, 0, 1,
 363                              prdt, ARRAY_SIZE(prdt), NULL);
 364    g_assert_cmphex(status, ==, 0);
 365    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 366
 367    /* Abort the request before it completes */
 368    status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,
 369                              prdt, ARRAY_SIZE(prdt), NULL);
 370    g_assert_cmphex(status, ==, 0);
 371    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 372}
 373
 374static void test_bmdma_one_sector_short_prdt(void)
 375{
 376    QPCIDevice *dev;
 377    QPCIBar bmdma_bar, ide_bar;
 378    uint8_t status;
 379
 380    /* Read 2 sectors but only give 1 sector in PRDT */
 381    PrdtEntry prdt[] = {
 382        {
 383            .addr = 0,
 384            .size = cpu_to_le32(0x200 | PRDT_EOT),
 385        },
 386    };
 387
 388    dev = get_pci_device(&bmdma_bar, &ide_bar);
 389
 390    /* Normal request */
 391    status = send_dma_request(CMD_READ_DMA, 0, 2,
 392                              prdt, ARRAY_SIZE(prdt), NULL);
 393    g_assert_cmphex(status, ==, 0);
 394    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 395
 396    /* Abort the request before it completes */
 397    status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 2,
 398                              prdt, ARRAY_SIZE(prdt), NULL);
 399    g_assert_cmphex(status, ==, 0);
 400    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 401}
 402
 403static void test_bmdma_long_prdt(void)
 404{
 405    QPCIDevice *dev;
 406    QPCIBar bmdma_bar, ide_bar;
 407    uint8_t status;
 408
 409    PrdtEntry prdt[] = {
 410        {
 411            .addr = 0,
 412            .size = cpu_to_le32(0x1000 | PRDT_EOT),
 413        },
 414    };
 415
 416    dev = get_pci_device(&bmdma_bar, &ide_bar);
 417
 418    /* Normal request */
 419    status = send_dma_request(CMD_READ_DMA, 0, 1,
 420                              prdt, ARRAY_SIZE(prdt), NULL);
 421    g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);
 422    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 423
 424    /* Abort the request before it completes */
 425    status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,
 426                              prdt, ARRAY_SIZE(prdt), NULL);
 427    g_assert_cmphex(status, ==, BM_STS_INTR);
 428    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 429}
 430
 431static void test_bmdma_no_busmaster(void)
 432{
 433    QPCIDevice *dev;
 434    QPCIBar bmdma_bar, ide_bar;
 435    uint8_t status;
 436
 437    dev = get_pci_device(&bmdma_bar, &ide_bar);
 438
 439    /* No PRDT_EOT, each entry addr 0/size 64k, and in theory qemu shouldn't be
 440     * able to access it anyway because the Bus Master bit in the PCI command
 441     * register isn't set. This is complete nonsense, but it used to be pretty
 442     * good at confusing and occasionally crashing qemu. */
 443    PrdtEntry prdt[4096] = { };
 444
 445    status = send_dma_request(CMD_READ_DMA | CMDF_NO_BM, 0, 512,
 446                              prdt, ARRAY_SIZE(prdt), NULL);
 447
 448    /* Not entirely clear what the expected result is, but this is what we get
 449     * in practice. At least we want to be aware of any changes. */
 450    g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);
 451    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 452}
 453
 454static void test_bmdma_setup(void)
 455{
 456    ide_test_start(
 457        "-drive file=%s,if=ide,serial=%s,cache=writeback,format=raw "
 458        "-global ide-hd.ver=%s",
 459        tmp_path, "testdisk", "version");
 460    qtest_irq_intercept_in(global_qtest, "ioapic");
 461}
 462
 463static void test_bmdma_teardown(void)
 464{
 465    ide_test_quit();
 466}
 467
 468static void string_cpu_to_be16(uint16_t *s, size_t bytes)
 469{
 470    g_assert((bytes & 1) == 0);
 471    bytes /= 2;
 472
 473    while (bytes--) {
 474        *s = cpu_to_be16(*s);
 475        s++;
 476    }
 477}
 478
 479static void test_identify(void)
 480{
 481    QPCIDevice *dev;
 482    QPCIBar bmdma_bar, ide_bar;
 483    uint8_t data;
 484    uint16_t buf[256];
 485    int i;
 486    int ret;
 487
 488    ide_test_start(
 489        "-drive file=%s,if=ide,serial=%s,cache=writeback,format=raw "
 490        "-global ide-hd.ver=%s",
 491        tmp_path, "testdisk", "version");
 492
 493    dev = get_pci_device(&bmdma_bar, &ide_bar);
 494
 495    /* IDENTIFY command on device 0*/
 496    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 497    qpci_io_writeb(dev, ide_bar, reg_command, CMD_IDENTIFY);
 498
 499    /* Read in the IDENTIFY buffer and check registers */
 500    data = qpci_io_readb(dev, ide_bar, reg_device);
 501    g_assert_cmpint(data & DEV, ==, 0);
 502
 503    for (i = 0; i < 256; i++) {
 504        data = qpci_io_readb(dev, ide_bar, reg_status);
 505        assert_bit_set(data, DRDY | DRQ);
 506        assert_bit_clear(data, BSY | DF | ERR);
 507
 508        buf[i] = qpci_io_readw(dev, ide_bar, reg_data);
 509    }
 510
 511    data = qpci_io_readb(dev, ide_bar, reg_status);
 512    assert_bit_set(data, DRDY);
 513    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 514
 515    /* Check serial number/version in the buffer */
 516    string_cpu_to_be16(&buf[10], 20);
 517    ret = memcmp(&buf[10], "testdisk            ", 20);
 518    g_assert(ret == 0);
 519
 520    string_cpu_to_be16(&buf[23], 8);
 521    ret = memcmp(&buf[23], "version ", 8);
 522    g_assert(ret == 0);
 523
 524    /* Write cache enabled bit */
 525    assert_bit_set(buf[85], 0x20);
 526
 527    ide_test_quit();
 528}
 529
 530/*
 531 * Write sector 1 with random data to make IDE storage dirty
 532 * Needed for flush tests so that flushes actually go though the block layer
 533 */
 534static void make_dirty(uint8_t device)
 535{
 536    QPCIDevice *dev;
 537    QPCIBar bmdma_bar, ide_bar;
 538    uint8_t status;
 539    size_t len = 512;
 540    uintptr_t guest_buf;
 541    void* buf;
 542
 543    dev = get_pci_device(&bmdma_bar, &ide_bar);
 544
 545    guest_buf = guest_alloc(guest_malloc, len);
 546    buf = g_malloc(len);
 547    g_assert(guest_buf);
 548    g_assert(buf);
 549
 550    memwrite(guest_buf, buf, len);
 551
 552    PrdtEntry prdt[] = {
 553        {
 554            .addr = cpu_to_le32(guest_buf),
 555            .size = cpu_to_le32(len | PRDT_EOT),
 556        },
 557    };
 558
 559    status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt,
 560                              ARRAY_SIZE(prdt), NULL);
 561    g_assert_cmphex(status, ==, BM_STS_INTR);
 562    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 563
 564    g_free(buf);
 565}
 566
 567static void test_flush(void)
 568{
 569    QPCIDevice *dev;
 570    QPCIBar bmdma_bar, ide_bar;
 571    uint8_t data;
 572
 573    ide_test_start(
 574        "-drive file=blkdebug::%s,if=ide,cache=writeback,format=raw",
 575        tmp_path);
 576
 577    dev = get_pci_device(&bmdma_bar, &ide_bar);
 578
 579    qtest_irq_intercept_in(global_qtest, "ioapic");
 580
 581    /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
 582    make_dirty(0);
 583
 584    /* Delay the completion of the flush request until we explicitly do it */
 585    g_free(hmp("qemu-io ide0-hd0 \"break flush_to_os A\""));
 586
 587    /* FLUSH CACHE command on device 0*/
 588    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 589    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 590
 591    /* Check status while request is in flight*/
 592    data = qpci_io_readb(dev, ide_bar, reg_status);
 593    assert_bit_set(data, BSY | DRDY);
 594    assert_bit_clear(data, DF | ERR | DRQ);
 595
 596    /* Complete the command */
 597    g_free(hmp("qemu-io ide0-hd0 \"resume A\""));
 598
 599    /* Check registers */
 600    data = qpci_io_readb(dev, ide_bar, reg_device);
 601    g_assert_cmpint(data & DEV, ==, 0);
 602
 603    do {
 604        data = qpci_io_readb(dev, ide_bar, reg_status);
 605    } while (data & BSY);
 606
 607    assert_bit_set(data, DRDY);
 608    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 609
 610    ide_test_quit();
 611}
 612
 613static void test_retry_flush(const char *machine)
 614{
 615    QPCIDevice *dev;
 616    QPCIBar bmdma_bar, ide_bar;
 617    uint8_t data;
 618    const char *s;
 619
 620    prepare_blkdebug_script(debug_path, "flush_to_disk");
 621
 622    ide_test_start(
 623        "-drive file=blkdebug:%s:%s,if=ide,cache=writeback,format=raw,"
 624        "rerror=stop,werror=stop",
 625        debug_path, tmp_path);
 626
 627    dev = get_pci_device(&bmdma_bar, &ide_bar);
 628
 629    qtest_irq_intercept_in(global_qtest, "ioapic");
 630
 631    /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
 632    make_dirty(0);
 633
 634    /* FLUSH CACHE command on device 0*/
 635    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 636    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 637
 638    /* Check status while request is in flight*/
 639    data = qpci_io_readb(dev, ide_bar, reg_status);
 640    assert_bit_set(data, BSY | DRDY);
 641    assert_bit_clear(data, DF | ERR | DRQ);
 642
 643    qmp_eventwait("STOP");
 644
 645    /* Complete the command */
 646    s = "{'execute':'cont' }";
 647    qmp_discard_response(s);
 648
 649    /* Check registers */
 650    data = qpci_io_readb(dev, ide_bar, reg_device);
 651    g_assert_cmpint(data & DEV, ==, 0);
 652
 653    do {
 654        data = qpci_io_readb(dev, ide_bar, reg_status);
 655    } while (data & BSY);
 656
 657    assert_bit_set(data, DRDY);
 658    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 659
 660    ide_test_quit();
 661}
 662
 663static void test_flush_nodev(void)
 664{
 665    QPCIDevice *dev;
 666    QPCIBar bmdma_bar, ide_bar;
 667
 668    ide_test_start("");
 669
 670    dev = get_pci_device(&bmdma_bar, &ide_bar);
 671
 672    /* FLUSH CACHE command on device 0*/
 673    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 674    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 675
 676    /* Just testing that qemu doesn't crash... */
 677
 678    ide_test_quit();
 679}
 680
 681static void test_pci_retry_flush(void)
 682{
 683    test_retry_flush("pc");
 684}
 685
 686static void test_isa_retry_flush(void)
 687{
 688    test_retry_flush("isapc");
 689}
 690
 691typedef struct Read10CDB {
 692    uint8_t opcode;
 693    uint8_t flags;
 694    uint32_t lba;
 695    uint8_t reserved;
 696    uint16_t nblocks;
 697    uint8_t control;
 698    uint16_t padding;
 699} __attribute__((__packed__)) Read10CDB;
 700
 701static void send_scsi_cdb_read10(QPCIDevice *dev, QPCIBar ide_bar,
 702                                 uint64_t lba, int nblocks)
 703{
 704    Read10CDB pkt = { .padding = 0 };
 705    int i;
 706
 707    g_assert_cmpint(lba, <=, UINT32_MAX);
 708    g_assert_cmpint(nblocks, <=, UINT16_MAX);
 709    g_assert_cmpint(nblocks, >=, 0);
 710
 711    /* Construct SCSI CDB packet */
 712    pkt.opcode = 0x28;
 713    pkt.lba = cpu_to_be32(lba);
 714    pkt.nblocks = cpu_to_be16(nblocks);
 715
 716    /* Send Packet */
 717    for (i = 0; i < sizeof(Read10CDB)/2; i++) {
 718        qpci_io_writew(dev, ide_bar, reg_data,
 719                       le16_to_cpu(((uint16_t *)&pkt)[i]));
 720    }
 721}
 722
 723static void nsleep(int64_t nsecs)
 724{
 725    const struct timespec val = { .tv_nsec = nsecs };
 726    nanosleep(&val, NULL);
 727    clock_set(nsecs);
 728}
 729
 730static uint8_t ide_wait_clear(uint8_t flag)
 731{
 732    QPCIDevice *dev;
 733    QPCIBar bmdma_bar, ide_bar;
 734    uint8_t data;
 735    time_t st;
 736
 737    dev = get_pci_device(&bmdma_bar, &ide_bar);
 738
 739    /* Wait with a 5 second timeout */
 740    time(&st);
 741    while (true) {
 742        data = qpci_io_readb(dev, ide_bar, reg_status);
 743        if (!(data & flag)) {
 744            return data;
 745        }
 746        if (difftime(time(NULL), st) > 5.0) {
 747            break;
 748        }
 749        nsleep(400);
 750    }
 751    g_assert_not_reached();
 752}
 753
 754static void ide_wait_intr(int irq)
 755{
 756    time_t st;
 757    bool intr;
 758
 759    time(&st);
 760    while (true) {
 761        intr = get_irq(irq);
 762        if (intr) {
 763            return;
 764        }
 765        if (difftime(time(NULL), st) > 5.0) {
 766            break;
 767        }
 768        nsleep(400);
 769    }
 770
 771    g_assert_not_reached();
 772}
 773
 774static void cdrom_pio_impl(int nblocks)
 775{
 776    QPCIDevice *dev;
 777    QPCIBar bmdma_bar, ide_bar;
 778    FILE *fh;
 779    int patt_blocks = MAX(16, nblocks);
 780    size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;
 781    char *pattern = g_malloc(patt_len);
 782    size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;
 783    uint16_t *rx = g_malloc0(rxsize);
 784    int i, j;
 785    uint8_t data;
 786    uint16_t limit;
 787
 788    /* Prepopulate the CDROM with an interesting pattern */
 789    generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);
 790    fh = fopen(tmp_path, "w+");
 791    fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);
 792    fclose(fh);
 793
 794    ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
 795                   "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);
 796    dev = get_pci_device(&bmdma_bar, &ide_bar);
 797    qtest_irq_intercept_in(global_qtest, "ioapic");
 798
 799    /* PACKET command on device 0 */
 800    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 801    qpci_io_writeb(dev, ide_bar, reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);
 802    qpci_io_writeb(dev, ide_bar, reg_lba_high, (BYTE_COUNT_LIMIT >> 8 & 0xFF));
 803    qpci_io_writeb(dev, ide_bar, reg_command, CMD_PACKET);
 804    /* HP0: Check_Status_A State */
 805    nsleep(400);
 806    data = ide_wait_clear(BSY);
 807    /* HP1: Send_Packet State */
 808    assert_bit_set(data, DRQ | DRDY);
 809    assert_bit_clear(data, ERR | DF | BSY);
 810
 811    /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */
 812    send_scsi_cdb_read10(dev, ide_bar, 0, nblocks);
 813
 814    /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.
 815     * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.
 816     * We allow an odd limit only when the remaining transfer size is
 817     * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only
 818     * request n blocks, so our request size is always even.
 819     * For this reason, we assume there is never a hanging byte to fetch. */
 820    g_assert(!(rxsize & 1));
 821    limit = BYTE_COUNT_LIMIT & ~1;
 822    for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {
 823        size_t offset = i * (limit / 2);
 824        size_t rem = (rxsize / 2) - offset;
 825
 826        /* HP3: INTRQ_Wait */
 827        ide_wait_intr(IDE_PRIMARY_IRQ);
 828
 829        /* HP2: Check_Status_B (and clear IRQ) */
 830        data = ide_wait_clear(BSY);
 831        assert_bit_set(data, DRQ | DRDY);
 832        assert_bit_clear(data, ERR | DF | BSY);
 833
 834        /* HP4: Transfer_Data */
 835        for (j = 0; j < MIN((limit / 2), rem); j++) {
 836            rx[offset + j] = cpu_to_le16(qpci_io_readw(dev, ide_bar,
 837                                                       reg_data));
 838        }
 839    }
 840
 841    /* Check for final completion IRQ */
 842    ide_wait_intr(IDE_PRIMARY_IRQ);
 843
 844    /* Sanity check final state */
 845    data = ide_wait_clear(DRQ);
 846    assert_bit_set(data, DRDY);
 847    assert_bit_clear(data, DRQ | ERR | DF | BSY);
 848
 849    g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);
 850    g_free(pattern);
 851    g_free(rx);
 852    test_bmdma_teardown();
 853}
 854
 855static void test_cdrom_pio(void)
 856{
 857    cdrom_pio_impl(1);
 858}
 859
 860static void test_cdrom_pio_large(void)
 861{
 862    /* Test a few loops of the PIO DRQ mechanism. */
 863    cdrom_pio_impl(BYTE_COUNT_LIMIT * 4 / ATAPI_BLOCK_SIZE);
 864}
 865
 866
 867static void test_cdrom_dma(void)
 868{
 869    static const size_t len = ATAPI_BLOCK_SIZE;
 870    char *pattern = g_malloc(ATAPI_BLOCK_SIZE * 16);
 871    char *rx = g_malloc0(len);
 872    uintptr_t guest_buf;
 873    PrdtEntry prdt[1];
 874    FILE *fh;
 875
 876    ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
 877                   "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);
 878    qtest_irq_intercept_in(global_qtest, "ioapic");
 879
 880    guest_buf = guest_alloc(guest_malloc, len);
 881    prdt[0].addr = cpu_to_le32(guest_buf);
 882    prdt[0].size = cpu_to_le32(len | PRDT_EOT);
 883
 884    generate_pattern(pattern, ATAPI_BLOCK_SIZE * 16, ATAPI_BLOCK_SIZE);
 885    fh = fopen(tmp_path, "w+");
 886    fwrite(pattern, ATAPI_BLOCK_SIZE, 16, fh);
 887    fclose(fh);
 888
 889    send_dma_request(CMD_PACKET, 0, 1, prdt, 1, send_scsi_cdb_read10);
 890
 891    /* Read back data from guest memory into local qtest memory */
 892    memread(guest_buf, rx, len);
 893    g_assert_cmpint(memcmp(pattern, rx, len), ==, 0);
 894
 895    g_free(pattern);
 896    g_free(rx);
 897    test_bmdma_teardown();
 898}
 899
 900int main(int argc, char **argv)
 901{
 902    const char *arch = qtest_get_arch();
 903    int fd;
 904    int ret;
 905
 906    /* Check architecture */
 907    if (strcmp(arch, "i386") && strcmp(arch, "x86_64")) {
 908        g_test_message("Skipping test for non-x86\n");
 909        return 0;
 910    }
 911
 912    /* Create temporary blkdebug instructions */
 913    fd = mkstemp(debug_path);
 914    g_assert(fd >= 0);
 915    close(fd);
 916
 917    /* Create a temporary raw image */
 918    fd = mkstemp(tmp_path);
 919    g_assert(fd >= 0);
 920    ret = ftruncate(fd, TEST_IMAGE_SIZE);
 921    g_assert(ret == 0);
 922    close(fd);
 923
 924    /* Run the tests */
 925    g_test_init(&argc, &argv, NULL);
 926
 927    qtest_add_func("/ide/identify", test_identify);
 928
 929    qtest_add_func("/ide/bmdma/setup", test_bmdma_setup);
 930    qtest_add_func("/ide/bmdma/simple_rw", test_bmdma_simple_rw);
 931    qtest_add_func("/ide/bmdma/short_prdt", test_bmdma_short_prdt);
 932    qtest_add_func("/ide/bmdma/one_sector_short_prdt",
 933                   test_bmdma_one_sector_short_prdt);
 934    qtest_add_func("/ide/bmdma/long_prdt", test_bmdma_long_prdt);
 935    qtest_add_func("/ide/bmdma/no_busmaster", test_bmdma_no_busmaster);
 936    qtest_add_func("/ide/bmdma/teardown", test_bmdma_teardown);
 937
 938    qtest_add_func("/ide/flush", test_flush);
 939    qtest_add_func("/ide/flush/nodev", test_flush_nodev);
 940    qtest_add_func("/ide/flush/retry_pci", test_pci_retry_flush);
 941    qtest_add_func("/ide/flush/retry_isa", test_isa_retry_flush);
 942
 943    qtest_add_func("/ide/cdrom/pio", test_cdrom_pio);
 944    qtest_add_func("/ide/cdrom/pio_large", test_cdrom_pio_large);
 945    qtest_add_func("/ide/cdrom/dma", test_cdrom_dma);
 946
 947    ret = g_test_run();
 948
 949    /* Cleanup */
 950    unlink(tmp_path);
 951    unlink(debug_path);
 952
 953    return ret;
 954}
 955