qemu/tests/qtest/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#include "qapi/qmp/qdict.h"
  33#include "qemu/bswap.h"
  34#include "hw/pci/pci_ids.h"
  35#include "hw/pci/pci_regs.h"
  36
  37/* TODO actually test the results and get rid of this */
  38#define qmp_discard_response(q, ...) qobject_unref(qtest_qmp(q, __VA_ARGS__))
  39
  40#define TEST_IMAGE_SIZE 64 * 1024 * 1024
  41
  42#define IDE_PCI_DEV     1
  43#define IDE_PCI_FUNC    1
  44
  45#define IDE_BASE 0x1f0
  46#define IDE_PRIMARY_IRQ 14
  47
  48#define ATAPI_BLOCK_SIZE 2048
  49
  50/* How many bytes to receive via ATAPI PIO at one time.
  51 * Must be less than 0xFFFF. */
  52#define BYTE_COUNT_LIMIT 5120
  53
  54enum {
  55    reg_data        = 0x0,
  56    reg_feature     = 0x1,
  57    reg_error       = 0x1,
  58    reg_nsectors    = 0x2,
  59    reg_lba_low     = 0x3,
  60    reg_lba_middle  = 0x4,
  61    reg_lba_high    = 0x5,
  62    reg_device      = 0x6,
  63    reg_status      = 0x7,
  64    reg_command     = 0x7,
  65};
  66
  67enum {
  68    BSY     = 0x80,
  69    DRDY    = 0x40,
  70    DF      = 0x20,
  71    DRQ     = 0x08,
  72    ERR     = 0x01,
  73};
  74
  75/* Error field */
  76enum {
  77    ABRT    = 0x04,
  78};
  79
  80enum {
  81    DEV     = 0x10,
  82    LBA     = 0x40,
  83};
  84
  85enum {
  86    bmreg_cmd       = 0x0,
  87    bmreg_status    = 0x2,
  88    bmreg_prdt      = 0x4,
  89};
  90
  91enum {
  92    CMD_DSM         = 0x06,
  93    CMD_DIAGNOSE    = 0x90,
  94    CMD_READ_DMA    = 0xc8,
  95    CMD_WRITE_DMA   = 0xca,
  96    CMD_FLUSH_CACHE = 0xe7,
  97    CMD_IDENTIFY    = 0xec,
  98    CMD_PACKET      = 0xa0,
  99
 100    CMDF_ABORT      = 0x100,
 101    CMDF_NO_BM      = 0x200,
 102};
 103
 104enum {
 105    BM_CMD_START    =  0x1,
 106    BM_CMD_WRITE    =  0x8, /* write = from device to memory */
 107};
 108
 109enum {
 110    BM_STS_ACTIVE   =  0x1,
 111    BM_STS_ERROR    =  0x2,
 112    BM_STS_INTR     =  0x4,
 113};
 114
 115enum {
 116    PRDT_EOT        = 0x80000000,
 117};
 118
 119#define assert_bit_set(data, mask) g_assert_cmphex((data) & (mask), ==, (mask))
 120#define assert_bit_clear(data, mask) g_assert_cmphex((data) & (mask), ==, 0)
 121
 122static QPCIBus *pcibus = NULL;
 123static QGuestAllocator guest_malloc;
 124
 125static char *tmp_path[2];
 126static char *debug_path;
 127
 128G_GNUC_PRINTF(1, 2)
 129static QTestState *ide_test_start(const char *cmdline_fmt, ...)
 130{
 131    QTestState *qts;
 132    g_autofree char *full_fmt = g_strdup_printf("-machine pc %s", cmdline_fmt);
 133    va_list ap;
 134
 135    va_start(ap, cmdline_fmt);
 136    qts = qtest_vinitf(full_fmt, ap);
 137    va_end(ap);
 138
 139    pc_alloc_init(&guest_malloc, qts, 0);
 140
 141    return qts;
 142}
 143
 144static void ide_test_quit(QTestState *qts)
 145{
 146    if (pcibus) {
 147        qpci_free_pc(pcibus);
 148        pcibus = NULL;
 149    }
 150    alloc_destroy(&guest_malloc);
 151    qtest_quit(qts);
 152}
 153
 154static QPCIDevice *get_pci_device(QTestState *qts, QPCIBar *bmdma_bar,
 155                                  QPCIBar *ide_bar)
 156{
 157    QPCIDevice *dev;
 158    uint16_t vendor_id, device_id;
 159
 160    if (!pcibus) {
 161        pcibus = qpci_new_pc(qts, NULL);
 162    }
 163
 164    /* Find PCI device and verify it's the right one */
 165    dev = qpci_device_find(pcibus, QPCI_DEVFN(IDE_PCI_DEV, IDE_PCI_FUNC));
 166    g_assert(dev != NULL);
 167
 168    vendor_id = qpci_config_readw(dev, PCI_VENDOR_ID);
 169    device_id = qpci_config_readw(dev, PCI_DEVICE_ID);
 170    g_assert(vendor_id == PCI_VENDOR_ID_INTEL);
 171    g_assert(device_id == PCI_DEVICE_ID_INTEL_82371SB_1);
 172
 173    /* Map bmdma BAR */
 174    *bmdma_bar = qpci_iomap(dev, 4, NULL);
 175
 176    *ide_bar = qpci_legacy_iomap(dev, IDE_BASE);
 177
 178    qpci_device_enable(dev);
 179
 180    return dev;
 181}
 182
 183static void free_pci_device(QPCIDevice *dev)
 184{
 185    /* libqos doesn't have a function for this, so free it manually */
 186    g_free(dev);
 187}
 188
 189typedef struct PrdtEntry {
 190    uint32_t addr;
 191    uint32_t size;
 192} QEMU_PACKED PrdtEntry;
 193
 194#define assert_bit_set(data, mask) g_assert_cmphex((data) & (mask), ==, (mask))
 195#define assert_bit_clear(data, mask) g_assert_cmphex((data) & (mask), ==, 0)
 196
 197static uint64_t trim_range_le(uint64_t sector, uint16_t count)
 198{
 199    /* 2-byte range, 6-byte LBA */
 200    return cpu_to_le64(((uint64_t)count << 48) + sector);
 201}
 202
 203static int send_dma_request(QTestState *qts, int cmd, uint64_t sector,
 204                            int nb_sectors, PrdtEntry *prdt, int prdt_entries,
 205                            void(*post_exec)(QPCIDevice *dev, QPCIBar ide_bar,
 206                                             uint64_t sector, int nb_sectors))
 207{
 208    QPCIDevice *dev;
 209    QPCIBar bmdma_bar, ide_bar;
 210    uintptr_t guest_prdt;
 211    size_t len;
 212    bool from_dev;
 213    uint8_t status;
 214    int flags;
 215
 216    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 217
 218    flags = cmd & ~0xff;
 219    cmd &= 0xff;
 220
 221    switch (cmd) {
 222    case CMD_READ_DMA:
 223    case CMD_PACKET:
 224        /* Assuming we only test data reads w/ ATAPI, otherwise we need to know
 225         * the SCSI command being sent in the packet, too. */
 226        from_dev = true;
 227        break;
 228    case CMD_DSM:
 229    case CMD_WRITE_DMA:
 230        from_dev = false;
 231        break;
 232    default:
 233        g_assert_not_reached();
 234    }
 235
 236    if (flags & CMDF_NO_BM) {
 237        qpci_config_writew(dev, PCI_COMMAND,
 238                           PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
 239    }
 240
 241    /* Select device 0 */
 242    qpci_io_writeb(dev, ide_bar, reg_device, 0 | LBA);
 243
 244    /* Stop any running transfer, clear any pending interrupt */
 245    qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 246    qpci_io_writeb(dev, bmdma_bar, bmreg_status, BM_STS_INTR);
 247
 248    /* Setup PRDT */
 249    len = sizeof(*prdt) * prdt_entries;
 250    guest_prdt = guest_alloc(&guest_malloc, len);
 251    qtest_memwrite(qts, guest_prdt, prdt, len);
 252    qpci_io_writel(dev, bmdma_bar, bmreg_prdt, guest_prdt);
 253
 254    /* ATA DMA command */
 255    if (cmd == CMD_PACKET) {
 256        /* Enables ATAPI DMA; otherwise PIO is attempted */
 257        qpci_io_writeb(dev, ide_bar, reg_feature, 0x01);
 258    } else {
 259        if (cmd == CMD_DSM) {
 260            /* trim bit */
 261            qpci_io_writeb(dev, ide_bar, reg_feature, 0x01);
 262        }
 263        qpci_io_writeb(dev, ide_bar, reg_nsectors, nb_sectors);
 264        qpci_io_writeb(dev, ide_bar, reg_lba_low,    sector & 0xff);
 265        qpci_io_writeb(dev, ide_bar, reg_lba_middle, (sector >> 8) & 0xff);
 266        qpci_io_writeb(dev, ide_bar, reg_lba_high,   (sector >> 16) & 0xff);
 267    }
 268
 269    qpci_io_writeb(dev, ide_bar, reg_command, cmd);
 270
 271    if (post_exec) {
 272        post_exec(dev, ide_bar, sector, nb_sectors);
 273    }
 274
 275    /* Start DMA transfer */
 276    qpci_io_writeb(dev, bmdma_bar, bmreg_cmd,
 277                   BM_CMD_START | (from_dev ? BM_CMD_WRITE : 0));
 278
 279    if (flags & CMDF_ABORT) {
 280        qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 281    }
 282
 283    /* Wait for the DMA transfer to complete */
 284    do {
 285        status = qpci_io_readb(dev, bmdma_bar, bmreg_status);
 286    } while ((status & (BM_STS_ACTIVE | BM_STS_INTR)) == BM_STS_ACTIVE);
 287
 288    g_assert_cmpint(qtest_get_irq(qts, IDE_PRIMARY_IRQ), ==,
 289                    !!(status & BM_STS_INTR));
 290
 291    /* Check IDE status code */
 292    assert_bit_set(qpci_io_readb(dev, ide_bar, reg_status), DRDY);
 293    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), BSY | DRQ);
 294
 295    /* Reading the status register clears the IRQ */
 296    g_assert(!qtest_get_irq(qts, IDE_PRIMARY_IRQ));
 297
 298    /* Stop DMA transfer if still active */
 299    if (status & BM_STS_ACTIVE) {
 300        qpci_io_writeb(dev, bmdma_bar, bmreg_cmd, 0);
 301    }
 302
 303    free_pci_device(dev);
 304
 305    return status;
 306}
 307
 308static QTestState *test_bmdma_setup(void)
 309{
 310    QTestState *qts;
 311
 312    qts = ide_test_start(
 313        "-drive file=%s,if=ide,cache=writeback,format=raw "
 314        "-global ide-hd.serial=%s -global ide-hd.ver=%s",
 315        tmp_path[0], "testdisk", "version");
 316    qtest_irq_intercept_in(qts, "ioapic");
 317
 318    return qts;
 319}
 320
 321static void test_bmdma_teardown(QTestState *qts)
 322{
 323    ide_test_quit(qts);
 324}
 325
 326static void test_bmdma_simple_rw(void)
 327{
 328    QTestState *qts;
 329    QPCIDevice *dev;
 330    QPCIBar bmdma_bar, ide_bar;
 331    uint8_t status;
 332    uint8_t *buf;
 333    uint8_t *cmpbuf;
 334    size_t len = 512;
 335    uintptr_t guest_buf;
 336    PrdtEntry prdt[1];
 337
 338    qts = test_bmdma_setup();
 339
 340    guest_buf  = guest_alloc(&guest_malloc, len);
 341    prdt[0].addr = cpu_to_le32(guest_buf);
 342    prdt[0].size = cpu_to_le32(len | PRDT_EOT);
 343
 344    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 345
 346    buf = g_malloc(len);
 347    cmpbuf = g_malloc(len);
 348
 349    /* Write 0x55 pattern to sector 0 */
 350    memset(buf, 0x55, len);
 351    qtest_memwrite(qts, guest_buf, buf, len);
 352
 353    status = send_dma_request(qts, CMD_WRITE_DMA, 0, 1, prdt,
 354                              ARRAY_SIZE(prdt), NULL);
 355    g_assert_cmphex(status, ==, BM_STS_INTR);
 356    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 357
 358    /* Write 0xaa pattern to sector 1 */
 359    memset(buf, 0xaa, len);
 360    qtest_memwrite(qts, guest_buf, buf, len);
 361
 362    status = send_dma_request(qts, CMD_WRITE_DMA, 1, 1, prdt,
 363                              ARRAY_SIZE(prdt), NULL);
 364    g_assert_cmphex(status, ==, BM_STS_INTR);
 365    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 366
 367    /* Read and verify 0x55 pattern in sector 0 */
 368    memset(cmpbuf, 0x55, len);
 369
 370    status = send_dma_request(qts, CMD_READ_DMA, 0, 1, prdt, ARRAY_SIZE(prdt),
 371                              NULL);
 372    g_assert_cmphex(status, ==, BM_STS_INTR);
 373    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 374
 375    qtest_memread(qts, guest_buf, buf, len);
 376    g_assert(memcmp(buf, cmpbuf, len) == 0);
 377
 378    /* Read and verify 0xaa pattern in sector 1 */
 379    memset(cmpbuf, 0xaa, len);
 380
 381    status = send_dma_request(qts, CMD_READ_DMA, 1, 1, prdt, ARRAY_SIZE(prdt),
 382                              NULL);
 383    g_assert_cmphex(status, ==, BM_STS_INTR);
 384    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 385
 386    qtest_memread(qts, guest_buf, buf, len);
 387    g_assert(memcmp(buf, cmpbuf, len) == 0);
 388
 389    free_pci_device(dev);
 390    g_free(buf);
 391    g_free(cmpbuf);
 392
 393    test_bmdma_teardown(qts);
 394}
 395
 396static void test_bmdma_trim(void)
 397{
 398    QTestState *qts;
 399    QPCIDevice *dev;
 400    QPCIBar bmdma_bar, ide_bar;
 401    uint8_t status;
 402    const uint64_t trim_range[] = { trim_range_le(0, 2),
 403                                    trim_range_le(6, 8),
 404                                    trim_range_le(10, 1),
 405                                  };
 406    const uint64_t bad_range = trim_range_le(TEST_IMAGE_SIZE / 512 - 1, 2);
 407    size_t len = 512;
 408    uint8_t *buf;
 409    uintptr_t guest_buf;
 410    PrdtEntry prdt[1];
 411
 412    qts = test_bmdma_setup();
 413
 414    guest_buf = guest_alloc(&guest_malloc, len);
 415    prdt[0].addr = cpu_to_le32(guest_buf),
 416    prdt[0].size = cpu_to_le32(len | PRDT_EOT),
 417
 418    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 419
 420    buf = g_malloc(len);
 421
 422    /* Normal request */
 423    *((uint64_t *)buf) = trim_range[0];
 424    *((uint64_t *)buf + 1) = trim_range[1];
 425
 426    qtest_memwrite(qts, guest_buf, buf, 2 * sizeof(uint64_t));
 427
 428    status = send_dma_request(qts, CMD_DSM, 0, 1, prdt,
 429                              ARRAY_SIZE(prdt), NULL);
 430    g_assert_cmphex(status, ==, BM_STS_INTR);
 431    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 432
 433    /* Request contains invalid range */
 434    *((uint64_t *)buf) = trim_range[2];
 435    *((uint64_t *)buf + 1) = bad_range;
 436
 437    qtest_memwrite(qts, guest_buf, buf, 2 * sizeof(uint64_t));
 438
 439    status = send_dma_request(qts, CMD_DSM, 0, 1, prdt,
 440                              ARRAY_SIZE(prdt), NULL);
 441    g_assert_cmphex(status, ==, BM_STS_INTR);
 442    assert_bit_set(qpci_io_readb(dev, ide_bar, reg_status), ERR);
 443    assert_bit_set(qpci_io_readb(dev, ide_bar, reg_error), ABRT);
 444
 445    free_pci_device(dev);
 446    g_free(buf);
 447    test_bmdma_teardown(qts);
 448}
 449
 450/*
 451 * This test is developed according to the Programming Interface for
 452 * Bus Master IDE Controller (Revision 1.0 5/16/94)
 453 */
 454static void test_bmdma_various_prdts(void)
 455{
 456    int sectors = 0;
 457    uint32_t size = 0;
 458
 459    for (sectors = 1; sectors <= 256; sectors *= 2) {
 460        QTestState *qts = NULL;
 461        QPCIDevice *dev = NULL;
 462        QPCIBar bmdma_bar, ide_bar;
 463
 464        qts = test_bmdma_setup();
 465        dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 466
 467        for (size = 0; size < 65536; size += 256) {
 468            uint32_t req_size = sectors * 512;
 469            uint32_t prd_size = size & 0xfffe; /* bit 0 is always set to 0 */
 470            uint8_t ret = 0;
 471            uint8_t req_status = 0;
 472            uint8_t abort_req_status = 0;
 473            PrdtEntry prdt[] = {
 474                {
 475                    .addr = 0,
 476                    .size = cpu_to_le32(size | PRDT_EOT),
 477                },
 478            };
 479
 480            /* A value of zero in PRD size indicates 64K */
 481            if (prd_size == 0) {
 482                prd_size = 65536;
 483            }
 484
 485            /*
 486             * 1. If PRDs specified a smaller size than the IDE transfer
 487             * size, then the Interrupt and Active bits in the Controller
 488             * status register are not set (Error Condition).
 489             *
 490             * 2. If the size of the physical memory regions was equal to
 491             * the IDE device transfer size, the Interrupt bit in the
 492             * Controller status register is set to 1, Active bit is set to 0.
 493             *
 494             * 3. If PRDs specified a larger size than the IDE transfer size,
 495             * the Interrupt and Active bits in the Controller status register
 496             * are both set to 1.
 497             */
 498            if (prd_size < req_size) {
 499                req_status = 0;
 500                abort_req_status = 0;
 501            } else if (prd_size == req_size) {
 502                req_status = BM_STS_INTR;
 503                abort_req_status = BM_STS_INTR;
 504            } else {
 505                req_status = BM_STS_ACTIVE | BM_STS_INTR;
 506                abort_req_status = BM_STS_INTR;
 507            }
 508
 509            /* Test the request */
 510            ret = send_dma_request(qts, CMD_READ_DMA, 0, sectors,
 511                                   prdt, ARRAY_SIZE(prdt), NULL);
 512            g_assert_cmphex(ret, ==, req_status);
 513            assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 514
 515            /* Now test aborting the same request */
 516            ret = send_dma_request(qts, CMD_READ_DMA | CMDF_ABORT, 0,
 517                                   sectors, prdt, ARRAY_SIZE(prdt), NULL);
 518            g_assert_cmphex(ret, ==, abort_req_status);
 519            assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 520        }
 521
 522        free_pci_device(dev);
 523        test_bmdma_teardown(qts);
 524    }
 525}
 526
 527static void test_bmdma_no_busmaster(void)
 528{
 529    QTestState *qts;
 530    QPCIDevice *dev;
 531    QPCIBar bmdma_bar, ide_bar;
 532    uint8_t status;
 533
 534    qts = test_bmdma_setup();
 535
 536    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 537
 538    /* No PRDT_EOT, each entry addr 0/size 64k, and in theory qemu shouldn't be
 539     * able to access it anyway because the Bus Master bit in the PCI command
 540     * register isn't set. This is complete nonsense, but it used to be pretty
 541     * good at confusing and occasionally crashing qemu. */
 542    PrdtEntry prdt[4096] = { };
 543
 544    status = send_dma_request(qts, CMD_READ_DMA | CMDF_NO_BM, 0, 512,
 545                              prdt, ARRAY_SIZE(prdt), NULL);
 546
 547    /* Not entirely clear what the expected result is, but this is what we get
 548     * in practice. At least we want to be aware of any changes. */
 549    g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);
 550    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 551    free_pci_device(dev);
 552    test_bmdma_teardown(qts);
 553}
 554
 555static void string_cpu_to_be16(uint16_t *s, size_t bytes)
 556{
 557    g_assert((bytes & 1) == 0);
 558    bytes /= 2;
 559
 560    while (bytes--) {
 561        *s = cpu_to_be16(*s);
 562        s++;
 563    }
 564}
 565
 566static void test_identify(void)
 567{
 568    QTestState *qts;
 569    QPCIDevice *dev;
 570    QPCIBar bmdma_bar, ide_bar;
 571    uint8_t data;
 572    uint16_t buf[256];
 573    int i;
 574    int ret;
 575
 576    qts = ide_test_start(
 577        "-drive file=%s,if=ide,cache=writeback,format=raw "
 578        "-global ide-hd.serial=%s -global ide-hd.ver=%s",
 579        tmp_path[0], "testdisk", "version");
 580
 581    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 582
 583    /* IDENTIFY command on device 0*/
 584    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 585    qpci_io_writeb(dev, ide_bar, reg_command, CMD_IDENTIFY);
 586
 587    /* Read in the IDENTIFY buffer and check registers */
 588    data = qpci_io_readb(dev, ide_bar, reg_device);
 589    g_assert_cmpint(data & DEV, ==, 0);
 590
 591    for (i = 0; i < 256; i++) {
 592        data = qpci_io_readb(dev, ide_bar, reg_status);
 593        assert_bit_set(data, DRDY | DRQ);
 594        assert_bit_clear(data, BSY | DF | ERR);
 595
 596        buf[i] = qpci_io_readw(dev, ide_bar, reg_data);
 597    }
 598
 599    data = qpci_io_readb(dev, ide_bar, reg_status);
 600    assert_bit_set(data, DRDY);
 601    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 602
 603    /* Check serial number/version in the buffer */
 604    string_cpu_to_be16(&buf[10], 20);
 605    ret = memcmp(&buf[10], "testdisk            ", 20);
 606    g_assert(ret == 0);
 607
 608    string_cpu_to_be16(&buf[23], 8);
 609    ret = memcmp(&buf[23], "version ", 8);
 610    g_assert(ret == 0);
 611
 612    /* Write cache enabled bit */
 613    assert_bit_set(buf[85], 0x20);
 614
 615    ide_test_quit(qts);
 616    free_pci_device(dev);
 617}
 618
 619static void test_diagnostic(void)
 620{
 621    QTestState *qts;
 622    QPCIDevice *dev;
 623    QPCIBar bmdma_bar, ide_bar;
 624    uint8_t data;
 625
 626    qts = ide_test_start(
 627        "-blockdev driver=file,node-name=hda,filename=%s "
 628        "-blockdev driver=file,node-name=hdb,filename=%s "
 629        "-device ide-hd,drive=hda,bus=ide.0,unit=0 "
 630        "-device ide-hd,drive=hdb,bus=ide.0,unit=1 ",
 631        tmp_path[0], tmp_path[1]);
 632
 633    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 634
 635    /* DIAGNOSE command on device 1 */
 636    qpci_io_writeb(dev, ide_bar, reg_device, DEV);
 637    data = qpci_io_readb(dev, ide_bar, reg_device);
 638    g_assert_cmphex(data & DEV, ==, DEV);
 639    qpci_io_writeb(dev, ide_bar, reg_command, CMD_DIAGNOSE);
 640
 641    /* Verify that DEVICE is now 0 */
 642    data = qpci_io_readb(dev, ide_bar, reg_device);
 643    g_assert_cmphex(data & DEV, ==, 0);
 644
 645    ide_test_quit(qts);
 646    free_pci_device(dev);
 647}
 648
 649/*
 650 * Write sector 1 with random data to make IDE storage dirty
 651 * Needed for flush tests so that flushes actually go though the block layer
 652 */
 653static void make_dirty(QTestState *qts, uint8_t device)
 654{
 655    QPCIDevice *dev;
 656    QPCIBar bmdma_bar, ide_bar;
 657    uint8_t status;
 658    size_t len = 512;
 659    uintptr_t guest_buf;
 660    void* buf;
 661
 662    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 663
 664    guest_buf = guest_alloc(&guest_malloc, len);
 665    buf = g_malloc(len);
 666    memset(buf, rand() % 255 + 1, len);
 667    g_assert(guest_buf);
 668    g_assert(buf);
 669
 670    qtest_memwrite(qts, guest_buf, buf, len);
 671
 672    PrdtEntry prdt[] = {
 673        {
 674            .addr = cpu_to_le32(guest_buf),
 675            .size = cpu_to_le32(len | PRDT_EOT),
 676        },
 677    };
 678
 679    status = send_dma_request(qts, CMD_WRITE_DMA, 1, 1, prdt,
 680                              ARRAY_SIZE(prdt), NULL);
 681    g_assert_cmphex(status, ==, BM_STS_INTR);
 682    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
 683
 684    g_free(buf);
 685    free_pci_device(dev);
 686}
 687
 688static void test_flush(void)
 689{
 690    QTestState *qts;
 691    QPCIDevice *dev;
 692    QPCIBar bmdma_bar, ide_bar;
 693    uint8_t data;
 694
 695    qts = ide_test_start(
 696        "-drive file=blkdebug::%s,if=ide,cache=writeback,format=raw",
 697        tmp_path[0]);
 698
 699    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 700
 701    qtest_irq_intercept_in(qts, "ioapic");
 702
 703    /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
 704    make_dirty(qts, 0);
 705
 706    /* Delay the completion of the flush request until we explicitly do it */
 707    g_free(qtest_hmp(qts, "qemu-io ide0-hd0 \"break flush_to_os A\""));
 708
 709    /* FLUSH CACHE command on device 0*/
 710    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 711    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 712
 713    /* Check status while request is in flight*/
 714    data = qpci_io_readb(dev, ide_bar, reg_status);
 715    assert_bit_set(data, BSY | DRDY);
 716    assert_bit_clear(data, DF | ERR | DRQ);
 717
 718    /* Complete the command */
 719    g_free(qtest_hmp(qts, "qemu-io ide0-hd0 \"resume A\""));
 720
 721    /* Check registers */
 722    data = qpci_io_readb(dev, ide_bar, reg_device);
 723    g_assert_cmpint(data & DEV, ==, 0);
 724
 725    do {
 726        data = qpci_io_readb(dev, ide_bar, reg_status);
 727    } while (data & BSY);
 728
 729    assert_bit_set(data, DRDY);
 730    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 731
 732    ide_test_quit(qts);
 733    free_pci_device(dev);
 734}
 735
 736static void test_pci_retry_flush(void)
 737{
 738    QTestState *qts;
 739    QPCIDevice *dev;
 740    QPCIBar bmdma_bar, ide_bar;
 741    uint8_t data;
 742
 743    prepare_blkdebug_script(debug_path, "flush_to_disk");
 744
 745    qts = ide_test_start(
 746        "-drive file=blkdebug:%s:%s,if=ide,cache=writeback,format=raw,"
 747        "rerror=stop,werror=stop",
 748        debug_path, tmp_path[0]);
 749
 750    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 751
 752    qtest_irq_intercept_in(qts, "ioapic");
 753
 754    /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
 755    make_dirty(qts, 0);
 756
 757    /* FLUSH CACHE command on device 0*/
 758    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 759    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 760
 761    /* Check status while request is in flight*/
 762    data = qpci_io_readb(dev, ide_bar, reg_status);
 763    assert_bit_set(data, BSY | DRDY);
 764    assert_bit_clear(data, DF | ERR | DRQ);
 765
 766    qtest_qmp_eventwait(qts, "STOP");
 767
 768    /* Complete the command */
 769    qmp_discard_response(qts, "{'execute':'cont' }");
 770
 771    /* Check registers */
 772    data = qpci_io_readb(dev, ide_bar, reg_device);
 773    g_assert_cmpint(data & DEV, ==, 0);
 774
 775    do {
 776        data = qpci_io_readb(dev, ide_bar, reg_status);
 777    } while (data & BSY);
 778
 779    assert_bit_set(data, DRDY);
 780    assert_bit_clear(data, BSY | DF | ERR | DRQ);
 781
 782    ide_test_quit(qts);
 783    free_pci_device(dev);
 784}
 785
 786static void test_flush_nodev(void)
 787{
 788    QTestState *qts;
 789    QPCIDevice *dev;
 790    QPCIBar bmdma_bar, ide_bar;
 791
 792    qts = ide_test_start("%s", "");
 793
 794    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 795
 796    /* FLUSH CACHE command on device 0*/
 797    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 798    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 799
 800    /* Just testing that qemu doesn't crash... */
 801
 802    free_pci_device(dev);
 803    ide_test_quit(qts);
 804}
 805
 806static void test_flush_empty_drive(void)
 807{
 808    QTestState *qts;
 809    QPCIDevice *dev;
 810    QPCIBar bmdma_bar, ide_bar;
 811
 812    qts = ide_test_start("-device ide-cd,bus=ide.0");
 813    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 814
 815    /* FLUSH CACHE command on device 0 */
 816    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 817    qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
 818
 819    /* Just testing that qemu doesn't crash... */
 820
 821    free_pci_device(dev);
 822    ide_test_quit(qts);
 823}
 824
 825typedef struct Read10CDB {
 826    uint8_t opcode;
 827    uint8_t flags;
 828    uint32_t lba;
 829    uint8_t reserved;
 830    uint16_t nblocks;
 831    uint8_t control;
 832    uint16_t padding;
 833} __attribute__((__packed__)) Read10CDB;
 834
 835static void send_scsi_cdb_read10(QPCIDevice *dev, QPCIBar ide_bar,
 836                                 uint64_t lba, int nblocks)
 837{
 838    Read10CDB pkt = { .padding = 0 };
 839    int i;
 840
 841    g_assert_cmpint(lba, <=, UINT32_MAX);
 842    g_assert_cmpint(nblocks, <=, UINT16_MAX);
 843    g_assert_cmpint(nblocks, >=, 0);
 844
 845    /* Construct SCSI CDB packet */
 846    pkt.opcode = 0x28;
 847    pkt.lba = cpu_to_be32(lba);
 848    pkt.nblocks = cpu_to_be16(nblocks);
 849
 850    /* Send Packet */
 851    for (i = 0; i < sizeof(Read10CDB)/2; i++) {
 852        qpci_io_writew(dev, ide_bar, reg_data,
 853                       le16_to_cpu(((uint16_t *)&pkt)[i]));
 854    }
 855}
 856
 857static void nsleep(QTestState *qts, int64_t nsecs)
 858{
 859    const struct timespec val = { .tv_nsec = nsecs };
 860    nanosleep(&val, NULL);
 861    qtest_clock_set(qts, nsecs);
 862}
 863
 864static uint8_t ide_wait_clear(QTestState *qts, uint8_t flag)
 865{
 866    QPCIDevice *dev;
 867    QPCIBar bmdma_bar, ide_bar;
 868    uint8_t data;
 869    time_t st;
 870
 871    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 872
 873    /* Wait with a 5 second timeout */
 874    time(&st);
 875    while (true) {
 876        data = qpci_io_readb(dev, ide_bar, reg_status);
 877        if (!(data & flag)) {
 878            free_pci_device(dev);
 879            return data;
 880        }
 881        if (difftime(time(NULL), st) > 5.0) {
 882            break;
 883        }
 884        nsleep(qts, 400);
 885    }
 886    g_assert_not_reached();
 887}
 888
 889static void ide_wait_intr(QTestState *qts, int irq)
 890{
 891    time_t st;
 892    bool intr;
 893
 894    time(&st);
 895    while (true) {
 896        intr = qtest_get_irq(qts, irq);
 897        if (intr) {
 898            return;
 899        }
 900        if (difftime(time(NULL), st) > 5.0) {
 901            break;
 902        }
 903        nsleep(qts, 400);
 904    }
 905
 906    g_assert_not_reached();
 907}
 908
 909static void cdrom_pio_impl(int nblocks)
 910{
 911    QTestState *qts;
 912    QPCIDevice *dev;
 913    QPCIBar bmdma_bar, ide_bar;
 914    FILE *fh;
 915    int patt_blocks = MAX(16, nblocks);
 916    size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;
 917    char *pattern = g_malloc(patt_len);
 918    size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;
 919    uint16_t *rx = g_malloc0(rxsize);
 920    int i, j;
 921    uint8_t data;
 922    uint16_t limit;
 923    size_t ret;
 924
 925    /* Prepopulate the CDROM with an interesting pattern */
 926    generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);
 927    fh = fopen(tmp_path[0], "wb+");
 928    ret = fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);
 929    g_assert_cmpint(ret, ==, patt_blocks);
 930    fclose(fh);
 931
 932    qts = ide_test_start(
 933            "-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
 934            "-device ide-cd,drive=sr0,bus=ide.0", tmp_path[0]);
 935    dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
 936    qtest_irq_intercept_in(qts, "ioapic");
 937
 938    /* PACKET command on device 0 */
 939    qpci_io_writeb(dev, ide_bar, reg_device, 0);
 940    qpci_io_writeb(dev, ide_bar, reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);
 941    qpci_io_writeb(dev, ide_bar, reg_lba_high, (BYTE_COUNT_LIMIT >> 8 & 0xFF));
 942    qpci_io_writeb(dev, ide_bar, reg_command, CMD_PACKET);
 943    /* HP0: Check_Status_A State */
 944    nsleep(qts, 400);
 945    data = ide_wait_clear(qts, BSY);
 946    /* HP1: Send_Packet State */
 947    assert_bit_set(data, DRQ | DRDY);
 948    assert_bit_clear(data, ERR | DF | BSY);
 949
 950    /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */
 951    send_scsi_cdb_read10(dev, ide_bar, 0, nblocks);
 952
 953    /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.
 954     * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.
 955     * We allow an odd limit only when the remaining transfer size is
 956     * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only
 957     * request n blocks, so our request size is always even.
 958     * For this reason, we assume there is never a hanging byte to fetch. */
 959    g_assert(!(rxsize & 1));
 960    limit = BYTE_COUNT_LIMIT & ~1;
 961    for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {
 962        size_t offset = i * (limit / 2);
 963        size_t rem = (rxsize / 2) - offset;
 964
 965        /* HP3: INTRQ_Wait */
 966        ide_wait_intr(qts, IDE_PRIMARY_IRQ);
 967
 968        /* HP2: Check_Status_B (and clear IRQ) */
 969        data = ide_wait_clear(qts, BSY);
 970        assert_bit_set(data, DRQ | DRDY);
 971        assert_bit_clear(data, ERR | DF | BSY);
 972
 973        /* HP4: Transfer_Data */
 974        for (j = 0; j < MIN((limit / 2), rem); j++) {
 975            rx[offset + j] = cpu_to_le16(qpci_io_readw(dev, ide_bar,
 976                                                       reg_data));
 977        }
 978    }
 979
 980    /* Check for final completion IRQ */
 981    ide_wait_intr(qts, IDE_PRIMARY_IRQ);
 982
 983    /* Sanity check final state */
 984    data = ide_wait_clear(qts, DRQ);
 985    assert_bit_set(data, DRDY);
 986    assert_bit_clear(data, DRQ | ERR | DF | BSY);
 987
 988    g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);
 989    g_free(pattern);
 990    g_free(rx);
 991    test_bmdma_teardown(qts);
 992    free_pci_device(dev);
 993}
 994
 995static void test_cdrom_pio(void)
 996{
 997    cdrom_pio_impl(1);
 998}
 999
1000static void test_cdrom_pio_large(void)
1001{
1002    /* Test a few loops of the PIO DRQ mechanism. */
1003    cdrom_pio_impl(BYTE_COUNT_LIMIT * 4 / ATAPI_BLOCK_SIZE);
1004}
1005
1006
1007static void test_cdrom_dma(void)
1008{
1009    QTestState *qts;
1010    static const size_t len = ATAPI_BLOCK_SIZE;
1011    size_t ret;
1012    char *pattern = g_malloc(ATAPI_BLOCK_SIZE * 16);
1013    char *rx = g_malloc0(len);
1014    uintptr_t guest_buf;
1015    PrdtEntry prdt[1];
1016    FILE *fh;
1017
1018    qts = ide_test_start(
1019            "-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
1020            "-device ide-cd,drive=sr0,bus=ide.0", tmp_path[0]);
1021    qtest_irq_intercept_in(qts, "ioapic");
1022
1023    guest_buf = guest_alloc(&guest_malloc, len);
1024    prdt[0].addr = cpu_to_le32(guest_buf);
1025    prdt[0].size = cpu_to_le32(len | PRDT_EOT);
1026
1027    generate_pattern(pattern, ATAPI_BLOCK_SIZE * 16, ATAPI_BLOCK_SIZE);
1028    fh = fopen(tmp_path[0], "wb+");
1029    ret = fwrite(pattern, ATAPI_BLOCK_SIZE, 16, fh);
1030    g_assert_cmpint(ret, ==, 16);
1031    fclose(fh);
1032
1033    send_dma_request(qts, CMD_PACKET, 0, 1, prdt, 1, send_scsi_cdb_read10);
1034
1035    /* Read back data from guest memory into local qtest memory */
1036    qtest_memread(qts, guest_buf, rx, len);
1037    g_assert_cmpint(memcmp(pattern, rx, len), ==, 0);
1038
1039    g_free(pattern);
1040    g_free(rx);
1041    test_bmdma_teardown(qts);
1042}
1043
1044int main(int argc, char **argv)
1045{
1046    const char *base;
1047    int i;
1048    int fd;
1049    int ret;
1050
1051    /*
1052     * "base" stores the starting point where we create temporary files.
1053     *
1054     * On Windows, this is set to the relative path of current working
1055     * directory, because the absolute path causes the blkdebug filename
1056     * parser fail to parse "blkdebug:path/to/config:path/to/image".
1057     */
1058#ifndef _WIN32
1059    base = g_get_tmp_dir();
1060#else
1061    base = ".";
1062#endif
1063
1064    /* Create temporary blkdebug instructions */
1065    debug_path = g_strdup_printf("%s/qtest-blkdebug.XXXXXX", base);
1066    fd = g_mkstemp(debug_path);
1067    g_assert(fd >= 0);
1068    close(fd);
1069
1070    /* Create a temporary raw image */
1071    for (i = 0; i < 2; ++i) {
1072        tmp_path[i] = g_strdup_printf("%s/qtest.XXXXXX", base);
1073        fd = g_mkstemp(tmp_path[i]);
1074        g_assert(fd >= 0);
1075        ret = ftruncate(fd, TEST_IMAGE_SIZE);
1076        g_assert(ret == 0);
1077        close(fd);
1078    }
1079
1080    /* Run the tests */
1081    g_test_init(&argc, &argv, NULL);
1082
1083    qtest_add_func("/ide/identify", test_identify);
1084
1085    qtest_add_func("/ide/diagnostic", test_diagnostic);
1086
1087    qtest_add_func("/ide/bmdma/simple_rw", test_bmdma_simple_rw);
1088    qtest_add_func("/ide/bmdma/trim", test_bmdma_trim);
1089    qtest_add_func("/ide/bmdma/various_prdts", test_bmdma_various_prdts);
1090    qtest_add_func("/ide/bmdma/no_busmaster", test_bmdma_no_busmaster);
1091
1092    qtest_add_func("/ide/flush", test_flush);
1093    qtest_add_func("/ide/flush/nodev", test_flush_nodev);
1094    qtest_add_func("/ide/flush/empty_drive", test_flush_empty_drive);
1095    qtest_add_func("/ide/flush/retry_pci", test_pci_retry_flush);
1096
1097    qtest_add_func("/ide/cdrom/pio", test_cdrom_pio);
1098    qtest_add_func("/ide/cdrom/pio_large", test_cdrom_pio_large);
1099    qtest_add_func("/ide/cdrom/dma", test_cdrom_dma);
1100
1101    ret = g_test_run();
1102
1103    /* Cleanup */
1104    for (i = 0; i < 2; ++i) {
1105        unlink(tmp_path[i]);
1106        g_free(tmp_path[i]);
1107    }
1108    unlink(debug_path);
1109    g_free(debug_path);
1110
1111    return ret;
1112}
1113