xref: /openbmc/qemu/tests/qtest/ide-test.c (revision 9f6ece49)
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 /* Specified by ATA (physical) CHS geometry for ~64 MiB device.  */
38 #define TEST_IMAGE_SIZE ((130 * 16 * 63) * 512)
39 
40 #define IDE_PCI_DEV     1
41 #define IDE_PCI_FUNC    1
42 
43 #define IDE_BASE 0x1f0
44 #define IDE_PRIMARY_IRQ 14
45 
46 #define ATAPI_BLOCK_SIZE 2048
47 
48 /* How many bytes to receive via ATAPI PIO at one time.
49  * Must be less than 0xFFFF. */
50 #define BYTE_COUNT_LIMIT 5120
51 
52 enum {
53     reg_data        = 0x0,
54     reg_feature     = 0x1,
55     reg_error       = 0x1,
56     reg_nsectors    = 0x2,
57     reg_lba_low     = 0x3,
58     reg_lba_middle  = 0x4,
59     reg_lba_high    = 0x5,
60     reg_device      = 0x6,
61     reg_status      = 0x7,
62     reg_command     = 0x7,
63 };
64 
65 enum {
66     BSY     = 0x80,
67     DRDY    = 0x40,
68     DF      = 0x20,
69     DRQ     = 0x08,
70     ERR     = 0x01,
71 };
72 
73 /* Error field */
74 enum {
75     ABRT    = 0x04,
76 };
77 
78 enum {
79     DEV     = 0x10,
80     LBA     = 0x40,
81 };
82 
83 enum {
84     bmreg_cmd       = 0x0,
85     bmreg_status    = 0x2,
86     bmreg_prdt      = 0x4,
87 };
88 
89 enum {
90     CMD_DSM         = 0x06,
91     CMD_DIAGNOSE    = 0x90,
92     CMD_INIT_DP     = 0x91,  /* INITIALIZE DEVICE PARAMETERS */
93     CMD_READ_DMA    = 0xc8,
94     CMD_WRITE_DMA   = 0xca,
95     CMD_FLUSH_CACHE = 0xe7,
96     CMD_IDENTIFY    = 0xec,
97     CMD_PACKET      = 0xa0,
98     CMD_READ_NATIVE = 0xf8,  /* READ NATIVE MAX ADDRESS */
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[2];
126 static char *debug_path;
127 
128 G_GNUC_PRINTF(1, 2)
129 static 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 
144 static 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 
154 static 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 
183 static 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 
189 typedef 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 
197 static 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 
203 static 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 
308 static 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 
321 static void test_bmdma_teardown(QTestState *qts)
322 {
323     ide_test_quit(qts);
324 }
325 
326 static 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 
396 static 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  */
454 static 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 
527 static 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 
555 static 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 
566 static void test_specify(void)
567 {
568     QTestState *qts;
569     QPCIDevice *dev;
570     QPCIBar bmdma_bar, ide_bar;
571     uint16_t cyls;
572     uint8_t heads, spt;
573 
574     qts = ide_test_start(
575         "-blockdev driver=file,node-name=hda,filename=%s "
576         "-device ide-hd,drive=hda,bus=ide.0,unit=0 ",
577         tmp_path[0]);
578 
579     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
580 
581     /* Initialize drive with zero sectors per track and one head.  */
582     qpci_io_writeb(dev, ide_bar, reg_nsectors, 0);
583     qpci_io_writeb(dev, ide_bar, reg_device, 0);
584     qpci_io_writeb(dev, ide_bar, reg_command, CMD_INIT_DP);
585 
586     /* READ NATIVE MAX ADDRESS (CHS mode).  */
587     qpci_io_writeb(dev, ide_bar, reg_device, 0xa0);
588     qpci_io_writeb(dev, ide_bar, reg_command, CMD_READ_NATIVE);
589 
590     heads = qpci_io_readb(dev, ide_bar, reg_device) & 0xf;
591     ++heads;
592     g_assert_cmpint(heads, ==, 16);
593 
594     cyls = qpci_io_readb(dev, ide_bar, reg_lba_high) << 8;
595     cyls |= qpci_io_readb(dev, ide_bar, reg_lba_middle);
596     ++cyls;
597     g_assert_cmpint(cyls, ==, 130);
598 
599     spt = qpci_io_readb(dev, ide_bar, reg_lba_low);
600     g_assert_cmpint(spt, ==, 63);
601 
602     ide_test_quit(qts);
603     free_pci_device(dev);
604 }
605 
606 static void test_identify(void)
607 {
608     QTestState *qts;
609     QPCIDevice *dev;
610     QPCIBar bmdma_bar, ide_bar;
611     uint8_t data;
612     uint16_t buf[256];
613     int i;
614     int ret;
615 
616     qts = ide_test_start(
617         "-drive file=%s,if=ide,cache=writeback,format=raw "
618         "-global ide-hd.serial=%s -global ide-hd.ver=%s",
619         tmp_path[0], "testdisk", "version");
620 
621     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
622 
623     /* IDENTIFY command on device 0*/
624     qpci_io_writeb(dev, ide_bar, reg_device, 0);
625     qpci_io_writeb(dev, ide_bar, reg_command, CMD_IDENTIFY);
626 
627     /* Read in the IDENTIFY buffer and check registers */
628     data = qpci_io_readb(dev, ide_bar, reg_device);
629     g_assert_cmpint(data & DEV, ==, 0);
630 
631     for (i = 0; i < 256; i++) {
632         data = qpci_io_readb(dev, ide_bar, reg_status);
633         assert_bit_set(data, DRDY | DRQ);
634         assert_bit_clear(data, BSY | DF | ERR);
635 
636         buf[i] = qpci_io_readw(dev, ide_bar, reg_data);
637     }
638 
639     data = qpci_io_readb(dev, ide_bar, reg_status);
640     assert_bit_set(data, DRDY);
641     assert_bit_clear(data, BSY | DF | ERR | DRQ);
642 
643     /* Check serial number/version in the buffer */
644     string_cpu_to_be16(&buf[10], 20);
645     ret = memcmp(&buf[10], "testdisk            ", 20);
646     g_assert(ret == 0);
647 
648     string_cpu_to_be16(&buf[23], 8);
649     ret = memcmp(&buf[23], "version ", 8);
650     g_assert(ret == 0);
651 
652     /* Write cache enabled bit */
653     assert_bit_set(buf[85], 0x20);
654 
655     ide_test_quit(qts);
656     free_pci_device(dev);
657 }
658 
659 static void test_diagnostic(void)
660 {
661     QTestState *qts;
662     QPCIDevice *dev;
663     QPCIBar bmdma_bar, ide_bar;
664     uint8_t data;
665 
666     qts = ide_test_start(
667         "-blockdev driver=file,node-name=hda,filename=%s "
668         "-blockdev driver=file,node-name=hdb,filename=%s "
669         "-device ide-hd,drive=hda,bus=ide.0,unit=0 "
670         "-device ide-hd,drive=hdb,bus=ide.0,unit=1 ",
671         tmp_path[0], tmp_path[1]);
672 
673     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
674 
675     /* DIAGNOSE command on device 1 */
676     qpci_io_writeb(dev, ide_bar, reg_device, DEV);
677     data = qpci_io_readb(dev, ide_bar, reg_device);
678     g_assert_cmphex(data & DEV, ==, DEV);
679     qpci_io_writeb(dev, ide_bar, reg_command, CMD_DIAGNOSE);
680 
681     /* Verify that DEVICE is now 0 */
682     data = qpci_io_readb(dev, ide_bar, reg_device);
683     g_assert_cmphex(data & DEV, ==, 0);
684 
685     ide_test_quit(qts);
686     free_pci_device(dev);
687 }
688 
689 /*
690  * Write sector 1 with random data to make IDE storage dirty
691  * Needed for flush tests so that flushes actually go though the block layer
692  */
693 static void make_dirty(QTestState *qts, uint8_t device)
694 {
695     QPCIDevice *dev;
696     QPCIBar bmdma_bar, ide_bar;
697     uint8_t status;
698     size_t len = 512;
699     uintptr_t guest_buf;
700     void* buf;
701 
702     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
703 
704     guest_buf = guest_alloc(&guest_malloc, len);
705     buf = g_malloc(len);
706     memset(buf, rand() % 255 + 1, len);
707     g_assert(guest_buf);
708     g_assert(buf);
709 
710     qtest_memwrite(qts, guest_buf, buf, len);
711 
712     PrdtEntry prdt[] = {
713         {
714             .addr = cpu_to_le32(guest_buf),
715             .size = cpu_to_le32(len | PRDT_EOT),
716         },
717     };
718 
719     status = send_dma_request(qts, CMD_WRITE_DMA, 1, 1, prdt,
720                               ARRAY_SIZE(prdt), NULL);
721     g_assert_cmphex(status, ==, BM_STS_INTR);
722     assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);
723 
724     g_free(buf);
725     free_pci_device(dev);
726 }
727 
728 static void test_flush(void)
729 {
730     QTestState *qts;
731     QPCIDevice *dev;
732     QPCIBar bmdma_bar, ide_bar;
733     uint8_t data;
734 
735     qts = ide_test_start(
736         "-drive file=blkdebug::%s,if=ide,cache=writeback,format=raw",
737         tmp_path[0]);
738 
739     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
740 
741     qtest_irq_intercept_in(qts, "ioapic");
742 
743     /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
744     make_dirty(qts, 0);
745 
746     /* Delay the completion of the flush request until we explicitly do it */
747     g_free(qtest_hmp(qts, "qemu-io ide0-hd0 \"break flush_to_os A\""));
748 
749     /* FLUSH CACHE command on device 0*/
750     qpci_io_writeb(dev, ide_bar, reg_device, 0);
751     qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
752 
753     /* Check status while request is in flight*/
754     data = qpci_io_readb(dev, ide_bar, reg_status);
755     assert_bit_set(data, BSY | DRDY);
756     assert_bit_clear(data, DF | ERR | DRQ);
757 
758     /* Complete the command */
759     g_free(qtest_hmp(qts, "qemu-io ide0-hd0 \"resume A\""));
760 
761     /* Check registers */
762     data = qpci_io_readb(dev, ide_bar, reg_device);
763     g_assert_cmpint(data & DEV, ==, 0);
764 
765     do {
766         data = qpci_io_readb(dev, ide_bar, reg_status);
767     } while (data & BSY);
768 
769     assert_bit_set(data, DRDY);
770     assert_bit_clear(data, BSY | DF | ERR | DRQ);
771 
772     ide_test_quit(qts);
773     free_pci_device(dev);
774 }
775 
776 static void test_pci_retry_flush(void)
777 {
778     QTestState *qts;
779     QPCIDevice *dev;
780     QPCIBar bmdma_bar, ide_bar;
781     uint8_t data;
782 
783     prepare_blkdebug_script(debug_path, "flush_to_disk");
784 
785     qts = ide_test_start(
786         "-drive file=blkdebug:%s:%s,if=ide,cache=writeback,format=raw,"
787         "rerror=stop,werror=stop",
788         debug_path, tmp_path[0]);
789 
790     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
791 
792     qtest_irq_intercept_in(qts, "ioapic");
793 
794     /* Dirty media so that CMD_FLUSH_CACHE will actually go to disk */
795     make_dirty(qts, 0);
796 
797     /* FLUSH CACHE command on device 0*/
798     qpci_io_writeb(dev, ide_bar, reg_device, 0);
799     qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
800 
801     /* Check status while request is in flight*/
802     data = qpci_io_readb(dev, ide_bar, reg_status);
803     assert_bit_set(data, BSY | DRDY);
804     assert_bit_clear(data, DF | ERR | DRQ);
805 
806     qtest_qmp_eventwait(qts, "STOP");
807 
808     /* Complete the command */
809     qtest_qmp_assert_success(qts, "{'execute':'cont' }");
810 
811     /* Check registers */
812     data = qpci_io_readb(dev, ide_bar, reg_device);
813     g_assert_cmpint(data & DEV, ==, 0);
814 
815     do {
816         data = qpci_io_readb(dev, ide_bar, reg_status);
817     } while (data & BSY);
818 
819     assert_bit_set(data, DRDY);
820     assert_bit_clear(data, BSY | DF | ERR | DRQ);
821 
822     ide_test_quit(qts);
823     free_pci_device(dev);
824 }
825 
826 static void test_flush_nodev(void)
827 {
828     QTestState *qts;
829     QPCIDevice *dev;
830     QPCIBar bmdma_bar, ide_bar;
831 
832     qts = ide_test_start("%s", "");
833 
834     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
835 
836     /* FLUSH CACHE command on device 0*/
837     qpci_io_writeb(dev, ide_bar, reg_device, 0);
838     qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
839 
840     /* Just testing that qemu doesn't crash... */
841 
842     free_pci_device(dev);
843     ide_test_quit(qts);
844 }
845 
846 static void test_flush_empty_drive(void)
847 {
848     QTestState *qts;
849     QPCIDevice *dev;
850     QPCIBar bmdma_bar, ide_bar;
851 
852     qts = ide_test_start("-device ide-cd,bus=ide.0");
853     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
854 
855     /* FLUSH CACHE command on device 0 */
856     qpci_io_writeb(dev, ide_bar, reg_device, 0);
857     qpci_io_writeb(dev, ide_bar, reg_command, CMD_FLUSH_CACHE);
858 
859     /* Just testing that qemu doesn't crash... */
860 
861     free_pci_device(dev);
862     ide_test_quit(qts);
863 }
864 
865 typedef struct Read10CDB {
866     uint8_t opcode;
867     uint8_t flags;
868     uint32_t lba;
869     uint8_t reserved;
870     uint16_t nblocks;
871     uint8_t control;
872     uint16_t padding;
873 } __attribute__((__packed__)) Read10CDB;
874 
875 static void send_scsi_cdb_read10(QPCIDevice *dev, QPCIBar ide_bar,
876                                  uint64_t lba, int nblocks)
877 {
878     Read10CDB pkt = { .padding = 0 };
879     int i;
880 
881     g_assert_cmpint(lba, <=, UINT32_MAX);
882     g_assert_cmpint(nblocks, <=, UINT16_MAX);
883     g_assert_cmpint(nblocks, >=, 0);
884 
885     /* Construct SCSI CDB packet */
886     pkt.opcode = 0x28;
887     pkt.lba = cpu_to_be32(lba);
888     pkt.nblocks = cpu_to_be16(nblocks);
889 
890     /* Send Packet */
891     for (i = 0; i < sizeof(Read10CDB)/2; i++) {
892         qpci_io_writew(dev, ide_bar, reg_data,
893                        le16_to_cpu(((uint16_t *)&pkt)[i]));
894     }
895 }
896 
897 static void nsleep(QTestState *qts, int64_t nsecs)
898 {
899     const struct timespec val = { .tv_nsec = nsecs };
900     nanosleep(&val, NULL);
901     qtest_clock_set(qts, nsecs);
902 }
903 
904 static uint8_t ide_wait_clear(QTestState *qts, uint8_t flag)
905 {
906     QPCIDevice *dev;
907     QPCIBar bmdma_bar, ide_bar;
908     uint8_t data;
909     time_t st;
910 
911     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
912 
913     /* Wait with a 5 second timeout */
914     time(&st);
915     while (true) {
916         data = qpci_io_readb(dev, ide_bar, reg_status);
917         if (!(data & flag)) {
918             free_pci_device(dev);
919             return data;
920         }
921         if (difftime(time(NULL), st) > 5.0) {
922             break;
923         }
924         nsleep(qts, 400);
925     }
926     g_assert_not_reached();
927 }
928 
929 static void ide_wait_intr(QTestState *qts, int irq)
930 {
931     time_t st;
932     bool intr;
933 
934     time(&st);
935     while (true) {
936         intr = qtest_get_irq(qts, irq);
937         if (intr) {
938             return;
939         }
940         if (difftime(time(NULL), st) > 5.0) {
941             break;
942         }
943         nsleep(qts, 400);
944     }
945 
946     g_assert_not_reached();
947 }
948 
949 static void cdrom_pio_impl(int nblocks)
950 {
951     QTestState *qts;
952     QPCIDevice *dev;
953     QPCIBar bmdma_bar, ide_bar;
954     FILE *fh;
955     int patt_blocks = MAX(16, nblocks);
956     size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;
957     char *pattern = g_malloc(patt_len);
958     size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;
959     uint16_t *rx = g_malloc0(rxsize);
960     int i, j;
961     uint8_t data;
962     uint16_t limit;
963     size_t ret;
964 
965     /* Prepopulate the CDROM with an interesting pattern */
966     generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);
967     fh = fopen(tmp_path[0], "wb+");
968     ret = fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);
969     g_assert_cmpint(ret, ==, patt_blocks);
970     fclose(fh);
971 
972     qts = ide_test_start(
973             "-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
974             "-device ide-cd,drive=sr0,bus=ide.0", tmp_path[0]);
975     dev = get_pci_device(qts, &bmdma_bar, &ide_bar);
976     qtest_irq_intercept_in(qts, "ioapic");
977 
978     /* PACKET command on device 0 */
979     qpci_io_writeb(dev, ide_bar, reg_device, 0);
980     qpci_io_writeb(dev, ide_bar, reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);
981     qpci_io_writeb(dev, ide_bar, reg_lba_high, (BYTE_COUNT_LIMIT >> 8 & 0xFF));
982     qpci_io_writeb(dev, ide_bar, reg_command, CMD_PACKET);
983     /* HP0: Check_Status_A State */
984     nsleep(qts, 400);
985     data = ide_wait_clear(qts, BSY);
986     /* HP1: Send_Packet State */
987     assert_bit_set(data, DRQ | DRDY);
988     assert_bit_clear(data, ERR | DF | BSY);
989 
990     /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */
991     send_scsi_cdb_read10(dev, ide_bar, 0, nblocks);
992 
993     /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.
994      * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.
995      * We allow an odd limit only when the remaining transfer size is
996      * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only
997      * request n blocks, so our request size is always even.
998      * For this reason, we assume there is never a hanging byte to fetch. */
999     g_assert(!(rxsize & 1));
1000     limit = BYTE_COUNT_LIMIT & ~1;
1001     for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {
1002         size_t offset = i * (limit / 2);
1003         size_t rem = (rxsize / 2) - offset;
1004 
1005         /* HP3: INTRQ_Wait */
1006         ide_wait_intr(qts, IDE_PRIMARY_IRQ);
1007 
1008         /* HP2: Check_Status_B (and clear IRQ) */
1009         data = ide_wait_clear(qts, BSY);
1010         assert_bit_set(data, DRQ | DRDY);
1011         assert_bit_clear(data, ERR | DF | BSY);
1012 
1013         /* HP4: Transfer_Data */
1014         for (j = 0; j < MIN((limit / 2), rem); j++) {
1015             rx[offset + j] = cpu_to_le16(qpci_io_readw(dev, ide_bar,
1016                                                        reg_data));
1017         }
1018     }
1019 
1020     /* Check for final completion IRQ */
1021     ide_wait_intr(qts, IDE_PRIMARY_IRQ);
1022 
1023     /* Sanity check final state */
1024     data = ide_wait_clear(qts, DRQ);
1025     assert_bit_set(data, DRDY);
1026     assert_bit_clear(data, DRQ | ERR | DF | BSY);
1027 
1028     g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);
1029     g_free(pattern);
1030     g_free(rx);
1031     test_bmdma_teardown(qts);
1032     free_pci_device(dev);
1033 }
1034 
1035 static void test_cdrom_pio(void)
1036 {
1037     cdrom_pio_impl(1);
1038 }
1039 
1040 static void test_cdrom_pio_large(void)
1041 {
1042     /* Test a few loops of the PIO DRQ mechanism. */
1043     cdrom_pio_impl(BYTE_COUNT_LIMIT * 4 / ATAPI_BLOCK_SIZE);
1044 }
1045 
1046 
1047 static void test_cdrom_dma(void)
1048 {
1049     QTestState *qts;
1050     static const size_t len = ATAPI_BLOCK_SIZE;
1051     size_t ret;
1052     char *pattern = g_malloc(ATAPI_BLOCK_SIZE * 16);
1053     char *rx = g_malloc0(len);
1054     uintptr_t guest_buf;
1055     PrdtEntry prdt[1];
1056     FILE *fh;
1057 
1058     qts = ide_test_start(
1059             "-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
1060             "-device ide-cd,drive=sr0,bus=ide.0", tmp_path[0]);
1061     qtest_irq_intercept_in(qts, "ioapic");
1062 
1063     guest_buf = guest_alloc(&guest_malloc, len);
1064     prdt[0].addr = cpu_to_le32(guest_buf);
1065     prdt[0].size = cpu_to_le32(len | PRDT_EOT);
1066 
1067     generate_pattern(pattern, ATAPI_BLOCK_SIZE * 16, ATAPI_BLOCK_SIZE);
1068     fh = fopen(tmp_path[0], "wb+");
1069     ret = fwrite(pattern, ATAPI_BLOCK_SIZE, 16, fh);
1070     g_assert_cmpint(ret, ==, 16);
1071     fclose(fh);
1072 
1073     send_dma_request(qts, CMD_PACKET, 0, 1, prdt, 1, send_scsi_cdb_read10);
1074 
1075     /* Read back data from guest memory into local qtest memory */
1076     qtest_memread(qts, guest_buf, rx, len);
1077     g_assert_cmpint(memcmp(pattern, rx, len), ==, 0);
1078 
1079     g_free(pattern);
1080     g_free(rx);
1081     test_bmdma_teardown(qts);
1082 }
1083 
1084 int main(int argc, char **argv)
1085 {
1086     const char *base;
1087     int i;
1088     int fd;
1089     int ret;
1090 
1091     /*
1092      * "base" stores the starting point where we create temporary files.
1093      *
1094      * On Windows, this is set to the relative path of current working
1095      * directory, because the absolute path causes the blkdebug filename
1096      * parser fail to parse "blkdebug:path/to/config:path/to/image".
1097      */
1098 #ifndef _WIN32
1099     base = g_get_tmp_dir();
1100 #else
1101     base = ".";
1102 #endif
1103 
1104     /* Create temporary blkdebug instructions */
1105     debug_path = g_strdup_printf("%s/qtest-blkdebug.XXXXXX", base);
1106     fd = g_mkstemp(debug_path);
1107     g_assert(fd >= 0);
1108     close(fd);
1109 
1110     /* Create a temporary raw image */
1111     for (i = 0; i < 2; ++i) {
1112         tmp_path[i] = g_strdup_printf("%s/qtest.XXXXXX", base);
1113         fd = g_mkstemp(tmp_path[i]);
1114         g_assert(fd >= 0);
1115         ret = ftruncate(fd, TEST_IMAGE_SIZE);
1116         g_assert(ret == 0);
1117         close(fd);
1118     }
1119 
1120     /* Run the tests */
1121     g_test_init(&argc, &argv, NULL);
1122 
1123     qtest_add_func("/ide/read_native", test_specify);
1124 
1125     qtest_add_func("/ide/identify", test_identify);
1126 
1127     qtest_add_func("/ide/diagnostic", test_diagnostic);
1128 
1129     qtest_add_func("/ide/bmdma/simple_rw", test_bmdma_simple_rw);
1130     qtest_add_func("/ide/bmdma/trim", test_bmdma_trim);
1131     qtest_add_func("/ide/bmdma/various_prdts", test_bmdma_various_prdts);
1132     qtest_add_func("/ide/bmdma/no_busmaster", test_bmdma_no_busmaster);
1133 
1134     qtest_add_func("/ide/flush", test_flush);
1135     qtest_add_func("/ide/flush/nodev", test_flush_nodev);
1136     qtest_add_func("/ide/flush/empty_drive", test_flush_empty_drive);
1137     qtest_add_func("/ide/flush/retry_pci", test_pci_retry_flush);
1138 
1139     qtest_add_func("/ide/cdrom/pio", test_cdrom_pio);
1140     qtest_add_func("/ide/cdrom/pio_large", test_cdrom_pio_large);
1141     qtest_add_func("/ide/cdrom/dma", test_cdrom_dma);
1142 
1143     ret = g_test_run();
1144 
1145     /* Cleanup */
1146     for (i = 0; i < 2; ++i) {
1147         unlink(tmp_path[i]);
1148         g_free(tmp_path[i]);
1149     }
1150     unlink(debug_path);
1151     g_free(debug_path);
1152 
1153     return ret;
1154 }
1155