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