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