]> Git Repo - qemu.git/blob - tests/ahci-test.c
Merge remote-tracking branch 'remotes/kraxel/tags/pull-ipxe-20150903-1' into staging
[qemu.git] / tests / ahci-test.c
1 /*
2  * AHCI test cases
3  *
4  * Copyright (c) 2014 John Snow <[email protected]>
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 <stdint.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <getopt.h>
29 #include <glib.h>
30
31 #include "libqtest.h"
32 #include "libqos/libqos-pc.h"
33 #include "libqos/ahci.h"
34 #include "libqos/pci-pc.h"
35
36 #include "qemu-common.h"
37 #include "qemu/host-utils.h"
38
39 #include "hw/pci/pci_ids.h"
40 #include "hw/pci/pci_regs.h"
41
42 /* Test-specific defines -- in MiB */
43 #define TEST_IMAGE_SIZE_MB (200 * 1024)
44 #define TEST_IMAGE_SECTORS ((TEST_IMAGE_SIZE_MB / AHCI_SECTOR_SIZE)     \
45                             * 1024 * 1024)
46
47 /*** Globals ***/
48 static char tmp_path[] = "/tmp/qtest.XXXXXX";
49 static char debug_path[] = "/tmp/qtest-blkdebug.XXXXXX";
50 static bool ahci_pedantic;
51
52 /*** Function Declarations ***/
53 static void ahci_test_port_spec(AHCIQState *ahci, uint8_t port);
54 static void ahci_test_pci_spec(AHCIQState *ahci);
55 static void ahci_test_pci_caps(AHCIQState *ahci, uint16_t header,
56                                uint8_t offset);
57 static void ahci_test_satacap(AHCIQState *ahci, uint8_t offset);
58 static void ahci_test_msicap(AHCIQState *ahci, uint8_t offset);
59 static void ahci_test_pmcap(AHCIQState *ahci, uint8_t offset);
60
61 /*** Utilities ***/
62
63 static void string_bswap16(uint16_t *s, size_t bytes)
64 {
65     g_assert_cmphex((bytes & 1), ==, 0);
66     bytes /= 2;
67
68     while (bytes--) {
69         *s = bswap16(*s);
70         s++;
71     }
72 }
73
74 /**
75  * Verify that the transfer did not corrupt our state at all.
76  */
77 static void verify_state(AHCIQState *ahci)
78 {
79     int i, j;
80     uint32_t ahci_fingerprint;
81     uint64_t hba_base;
82     uint64_t hba_stored;
83     AHCICommandHeader cmd;
84
85     ahci_fingerprint = qpci_config_readl(ahci->dev, PCI_VENDOR_ID);
86     g_assert_cmphex(ahci_fingerprint, ==, ahci->fingerprint);
87
88     /* If we haven't initialized, this is as much as can be validated. */
89     if (!ahci->hba_base) {
90         return;
91     }
92
93     hba_base = (uint64_t)qpci_config_readl(ahci->dev, PCI_BASE_ADDRESS_5);
94     hba_stored = (uint64_t)(uintptr_t)ahci->hba_base;
95     g_assert_cmphex(hba_base, ==, hba_stored);
96
97     g_assert_cmphex(ahci_rreg(ahci, AHCI_CAP), ==, ahci->cap);
98     g_assert_cmphex(ahci_rreg(ahci, AHCI_CAP2), ==, ahci->cap2);
99
100     for (i = 0; i < 32; i++) {
101         g_assert_cmphex(ahci_px_rreg(ahci, i, AHCI_PX_FB), ==,
102                         ahci->port[i].fb);
103         g_assert_cmphex(ahci_px_rreg(ahci, i, AHCI_PX_CLB), ==,
104                         ahci->port[i].clb);
105         for (j = 0; j < 32; j++) {
106             ahci_get_command_header(ahci, i, j, &cmd);
107             g_assert_cmphex(cmd.prdtl, ==, ahci->port[i].prdtl[j]);
108             g_assert_cmphex(cmd.ctba, ==, ahci->port[i].ctba[j]);
109         }
110     }
111 }
112
113 static void ahci_migrate(AHCIQState *from, AHCIQState *to, const char *uri)
114 {
115     QOSState *tmp = to->parent;
116     QPCIDevice *dev = to->dev;
117     if (uri == NULL) {
118         uri = "tcp:127.0.0.1:1234";
119     }
120
121     /* context will be 'to' after completion. */
122     migrate(from->parent, to->parent, uri);
123
124     /* We'd like for the AHCIState objects to still point
125      * to information specific to its specific parent
126      * instance, but otherwise just inherit the new data. */
127     memcpy(to, from, sizeof(AHCIQState));
128     to->parent = tmp;
129     to->dev = dev;
130
131     tmp = from->parent;
132     dev = from->dev;
133     memset(from, 0x00, sizeof(AHCIQState));
134     from->parent = tmp;
135     from->dev = dev;
136
137     verify_state(to);
138 }
139
140 /*** Test Setup & Teardown ***/
141
142 /**
143  * Start a Q35 machine and bookmark a handle to the AHCI device.
144  */
145 static AHCIQState *ahci_vboot(const char *cli, va_list ap)
146 {
147     AHCIQState *s;
148
149     s = g_malloc0(sizeof(AHCIQState));
150     s->parent = qtest_pc_vboot(cli, ap);
151     alloc_set_flags(s->parent->alloc, ALLOC_LEAK_ASSERT);
152
153     /* Verify that we have an AHCI device present. */
154     s->dev = get_ahci_device(&s->fingerprint);
155
156     return s;
157 }
158
159 /**
160  * Start a Q35 machine and bookmark a handle to the AHCI device.
161  */
162 static AHCIQState *ahci_boot(const char *cli, ...)
163 {
164     AHCIQState *s;
165     va_list ap;
166
167     if (cli) {
168         va_start(ap, cli);
169         s = ahci_vboot(cli, ap);
170         va_end(ap);
171     } else {
172         cli = "-drive if=none,id=drive0,file=%s,cache=writeback,serial=%s"
173             ",format=qcow2"
174             " -M q35 "
175             "-device ide-hd,drive=drive0 "
176             "-global ide-hd.ver=%s";
177         s = ahci_boot(cli, tmp_path, "testdisk", "version");
178     }
179
180     return s;
181 }
182
183 /**
184  * Clean up the PCI device, then terminate the QEMU instance.
185  */
186 static void ahci_shutdown(AHCIQState *ahci)
187 {
188     QOSState *qs = ahci->parent;
189
190     set_context(qs);
191     ahci_clean_mem(ahci);
192     free_ahci_device(ahci->dev);
193     g_free(ahci);
194     qtest_shutdown(qs);
195 }
196
197 /**
198  * Boot and fully enable the HBA device.
199  * @see ahci_boot, ahci_pci_enable and ahci_hba_enable.
200  */
201 static AHCIQState *ahci_boot_and_enable(const char *cli, ...)
202 {
203     AHCIQState *ahci;
204     va_list ap;
205     uint16_t buff[256];
206     uint8_t port;
207
208     if (cli) {
209         va_start(ap, cli);
210         ahci = ahci_vboot(cli, ap);
211         va_end(ap);
212     } else {
213         ahci = ahci_boot(NULL);
214     }
215
216     ahci_pci_enable(ahci);
217     ahci_hba_enable(ahci);
218     /* Initialize test device */
219     port = ahci_port_select(ahci);
220     ahci_port_clear(ahci, port);
221     ahci_io(ahci, port, CMD_IDENTIFY, &buff, sizeof(buff), 0);
222
223     return ahci;
224 }
225
226 /*** Specification Adherence Tests ***/
227
228 /**
229  * Implementation for test_pci_spec. Ensures PCI configuration space is sane.
230  */
231 static void ahci_test_pci_spec(AHCIQState *ahci)
232 {
233     uint8_t datab;
234     uint16_t data;
235     uint32_t datal;
236
237     /* Most of these bits should start cleared until we turn them on. */
238     data = qpci_config_readw(ahci->dev, PCI_COMMAND);
239     ASSERT_BIT_CLEAR(data, PCI_COMMAND_MEMORY);
240     ASSERT_BIT_CLEAR(data, PCI_COMMAND_MASTER);
241     ASSERT_BIT_CLEAR(data, PCI_COMMAND_SPECIAL);     /* Reserved */
242     ASSERT_BIT_CLEAR(data, PCI_COMMAND_VGA_PALETTE); /* Reserved */
243     ASSERT_BIT_CLEAR(data, PCI_COMMAND_PARITY);
244     ASSERT_BIT_CLEAR(data, PCI_COMMAND_WAIT);        /* Reserved */
245     ASSERT_BIT_CLEAR(data, PCI_COMMAND_SERR);
246     ASSERT_BIT_CLEAR(data, PCI_COMMAND_FAST_BACK);
247     ASSERT_BIT_CLEAR(data, PCI_COMMAND_INTX_DISABLE);
248     ASSERT_BIT_CLEAR(data, 0xF800);                  /* Reserved */
249
250     data = qpci_config_readw(ahci->dev, PCI_STATUS);
251     ASSERT_BIT_CLEAR(data, 0x01 | 0x02 | 0x04);     /* Reserved */
252     ASSERT_BIT_CLEAR(data, PCI_STATUS_INTERRUPT);
253     ASSERT_BIT_SET(data, PCI_STATUS_CAP_LIST);      /* must be set */
254     ASSERT_BIT_CLEAR(data, PCI_STATUS_UDF);         /* Reserved */
255     ASSERT_BIT_CLEAR(data, PCI_STATUS_PARITY);
256     ASSERT_BIT_CLEAR(data, PCI_STATUS_SIG_TARGET_ABORT);
257     ASSERT_BIT_CLEAR(data, PCI_STATUS_REC_TARGET_ABORT);
258     ASSERT_BIT_CLEAR(data, PCI_STATUS_REC_MASTER_ABORT);
259     ASSERT_BIT_CLEAR(data, PCI_STATUS_SIG_SYSTEM_ERROR);
260     ASSERT_BIT_CLEAR(data, PCI_STATUS_DETECTED_PARITY);
261
262     /* RID occupies the low byte, CCs occupy the high three. */
263     datal = qpci_config_readl(ahci->dev, PCI_CLASS_REVISION);
264     if (ahci_pedantic) {
265         /* AHCI 1.3 specifies that at-boot, the RID should reset to 0x00,
266          * Though in practice this is likely seldom true. */
267         ASSERT_BIT_CLEAR(datal, 0xFF);
268     }
269
270     /* BCC *must* equal 0x01. */
271     g_assert_cmphex(PCI_BCC(datal), ==, 0x01);
272     if (PCI_SCC(datal) == 0x01) {
273         /* IDE */
274         ASSERT_BIT_SET(0x80000000, datal);
275         ASSERT_BIT_CLEAR(0x60000000, datal);
276     } else if (PCI_SCC(datal) == 0x04) {
277         /* RAID */
278         g_assert_cmphex(PCI_PI(datal), ==, 0);
279     } else if (PCI_SCC(datal) == 0x06) {
280         /* AHCI */
281         g_assert_cmphex(PCI_PI(datal), ==, 0x01);
282     } else {
283         g_assert_not_reached();
284     }
285
286     datab = qpci_config_readb(ahci->dev, PCI_CACHE_LINE_SIZE);
287     g_assert_cmphex(datab, ==, 0);
288
289     datab = qpci_config_readb(ahci->dev, PCI_LATENCY_TIMER);
290     g_assert_cmphex(datab, ==, 0);
291
292     /* Only the bottom 7 bits must be off. */
293     datab = qpci_config_readb(ahci->dev, PCI_HEADER_TYPE);
294     ASSERT_BIT_CLEAR(datab, 0x7F);
295
296     /* BIST is optional, but the low 7 bits must always start off regardless. */
297     datab = qpci_config_readb(ahci->dev, PCI_BIST);
298     ASSERT_BIT_CLEAR(datab, 0x7F);
299
300     /* BARS 0-4 do not have a boot spec, but ABAR/BAR5 must be clean. */
301     datal = qpci_config_readl(ahci->dev, PCI_BASE_ADDRESS_5);
302     g_assert_cmphex(datal, ==, 0);
303
304     qpci_config_writel(ahci->dev, PCI_BASE_ADDRESS_5, 0xFFFFFFFF);
305     datal = qpci_config_readl(ahci->dev, PCI_BASE_ADDRESS_5);
306     /* ABAR must be 32-bit, memory mapped, non-prefetchable and
307      * must be >= 512 bytes. To that end, bits 0-8 must be off. */
308     ASSERT_BIT_CLEAR(datal, 0xFF);
309
310     /* Capability list MUST be present, */
311     datal = qpci_config_readl(ahci->dev, PCI_CAPABILITY_LIST);
312     /* But these bits are reserved. */
313     ASSERT_BIT_CLEAR(datal, ~0xFF);
314     g_assert_cmphex(datal, !=, 0);
315
316     /* Check specification adherence for capability extenstions. */
317     data = qpci_config_readw(ahci->dev, datal);
318
319     switch (ahci->fingerprint) {
320     case AHCI_INTEL_ICH9:
321         /* Intel ICH9 Family Datasheet 14.1.19 p.550 */
322         g_assert_cmphex((data & 0xFF), ==, PCI_CAP_ID_MSI);
323         break;
324     default:
325         /* AHCI 1.3, Section 2.1.14 -- CAP must point to PMCAP. */
326         g_assert_cmphex((data & 0xFF), ==, PCI_CAP_ID_PM);
327     }
328
329     ahci_test_pci_caps(ahci, data, (uint8_t)datal);
330
331     /* Reserved. */
332     datal = qpci_config_readl(ahci->dev, PCI_CAPABILITY_LIST + 4);
333     g_assert_cmphex(datal, ==, 0);
334
335     /* IPIN might vary, but ILINE must be off. */
336     datab = qpci_config_readb(ahci->dev, PCI_INTERRUPT_LINE);
337     g_assert_cmphex(datab, ==, 0);
338 }
339
340 /**
341  * Test PCI capabilities for AHCI specification adherence.
342  */
343 static void ahci_test_pci_caps(AHCIQState *ahci, uint16_t header,
344                                uint8_t offset)
345 {
346     uint8_t cid = header & 0xFF;
347     uint8_t next = header >> 8;
348
349     g_test_message("CID: %02x; next: %02x", cid, next);
350
351     switch (cid) {
352     case PCI_CAP_ID_PM:
353         ahci_test_pmcap(ahci, offset);
354         break;
355     case PCI_CAP_ID_MSI:
356         ahci_test_msicap(ahci, offset);
357         break;
358     case PCI_CAP_ID_SATA:
359         ahci_test_satacap(ahci, offset);
360         break;
361
362     default:
363         g_test_message("Unknown CAP 0x%02x", cid);
364     }
365
366     if (next) {
367         ahci_test_pci_caps(ahci, qpci_config_readw(ahci->dev, next), next);
368     }
369 }
370
371 /**
372  * Test SATA PCI capabilitity for AHCI specification adherence.
373  */
374 static void ahci_test_satacap(AHCIQState *ahci, uint8_t offset)
375 {
376     uint16_t dataw;
377     uint32_t datal;
378
379     g_test_message("Verifying SATACAP");
380
381     /* Assert that the SATACAP version is 1.0, And reserved bits are empty. */
382     dataw = qpci_config_readw(ahci->dev, offset + 2);
383     g_assert_cmphex(dataw, ==, 0x10);
384
385     /* Grab the SATACR1 register. */
386     datal = qpci_config_readw(ahci->dev, offset + 4);
387
388     switch (datal & 0x0F) {
389     case 0x04: /* BAR0 */
390     case 0x05: /* BAR1 */
391     case 0x06:
392     case 0x07:
393     case 0x08:
394     case 0x09: /* BAR5 */
395     case 0x0F: /* Immediately following SATACR1 in PCI config space. */
396         break;
397     default:
398         /* Invalid BARLOC for the Index Data Pair. */
399         g_assert_not_reached();
400     }
401
402     /* Reserved. */
403     g_assert_cmphex((datal >> 24), ==, 0x00);
404 }
405
406 /**
407  * Test MSI PCI capability for AHCI specification adherence.
408  */
409 static void ahci_test_msicap(AHCIQState *ahci, uint8_t offset)
410 {
411     uint16_t dataw;
412     uint32_t datal;
413
414     g_test_message("Verifying MSICAP");
415
416     dataw = qpci_config_readw(ahci->dev, offset + PCI_MSI_FLAGS);
417     ASSERT_BIT_CLEAR(dataw, PCI_MSI_FLAGS_ENABLE);
418     ASSERT_BIT_CLEAR(dataw, PCI_MSI_FLAGS_QSIZE);
419     ASSERT_BIT_CLEAR(dataw, PCI_MSI_FLAGS_RESERVED);
420
421     datal = qpci_config_readl(ahci->dev, offset + PCI_MSI_ADDRESS_LO);
422     g_assert_cmphex(datal, ==, 0);
423
424     if (dataw & PCI_MSI_FLAGS_64BIT) {
425         g_test_message("MSICAP is 64bit");
426         datal = qpci_config_readl(ahci->dev, offset + PCI_MSI_ADDRESS_HI);
427         g_assert_cmphex(datal, ==, 0);
428         dataw = qpci_config_readw(ahci->dev, offset + PCI_MSI_DATA_64);
429         g_assert_cmphex(dataw, ==, 0);
430     } else {
431         g_test_message("MSICAP is 32bit");
432         dataw = qpci_config_readw(ahci->dev, offset + PCI_MSI_DATA_32);
433         g_assert_cmphex(dataw, ==, 0);
434     }
435 }
436
437 /**
438  * Test Power Management PCI capability for AHCI specification adherence.
439  */
440 static void ahci_test_pmcap(AHCIQState *ahci, uint8_t offset)
441 {
442     uint16_t dataw;
443
444     g_test_message("Verifying PMCAP");
445
446     dataw = qpci_config_readw(ahci->dev, offset + PCI_PM_PMC);
447     ASSERT_BIT_CLEAR(dataw, PCI_PM_CAP_PME_CLOCK);
448     ASSERT_BIT_CLEAR(dataw, PCI_PM_CAP_RESERVED);
449     ASSERT_BIT_CLEAR(dataw, PCI_PM_CAP_D1);
450     ASSERT_BIT_CLEAR(dataw, PCI_PM_CAP_D2);
451
452     dataw = qpci_config_readw(ahci->dev, offset + PCI_PM_CTRL);
453     ASSERT_BIT_CLEAR(dataw, PCI_PM_CTRL_STATE_MASK);
454     ASSERT_BIT_CLEAR(dataw, PCI_PM_CTRL_RESERVED);
455     ASSERT_BIT_CLEAR(dataw, PCI_PM_CTRL_DATA_SEL_MASK);
456     ASSERT_BIT_CLEAR(dataw, PCI_PM_CTRL_DATA_SCALE_MASK);
457 }
458
459 static void ahci_test_hba_spec(AHCIQState *ahci)
460 {
461     unsigned i;
462     uint32_t reg;
463     uint32_t ports;
464     uint8_t nports_impl;
465     uint8_t maxports;
466
467     g_assert(ahci != NULL);
468
469     /*
470      * Note that the AHCI spec does expect the BIOS to set up a few things:
471      * CAP.SSS    - Support for staggered spin-up            (t/f)
472      * CAP.SMPS   - Support for mechanical presence switches (t/f)
473      * PI         - Ports Implemented                        (1-32)
474      * PxCMD.HPCP - Hot Plug Capable Port
475      * PxCMD.MPSP - Mechanical Presence Switch Present
476      * PxCMD.CPD  - Cold Presence Detection support
477      *
478      * Additional items are touched if CAP.SSS is on, see AHCI 10.1.1 p.97:
479      * Foreach Port Implemented:
480      * -PxCMD.ST, PxCMD.CR, PxCMD.FRE, PxCMD.FR, PxSCTL.DET are 0
481      * -PxCLB/U and PxFB/U are set to valid regions in memory
482      * -PxSUD is set to 1.
483      * -PxSSTS.DET is polled for presence; if detected, we continue:
484      * -PxSERR is cleared with 1's.
485      * -If PxTFD.STS.BSY, PxTFD.STS.DRQ, and PxTFD.STS.ERR are all zero,
486      *  the device is ready.
487      */
488
489     /* 1 CAP - Capabilities Register */
490     ahci->cap = ahci_rreg(ahci, AHCI_CAP);
491     ASSERT_BIT_CLEAR(ahci->cap, AHCI_CAP_RESERVED);
492
493     /* 2 GHC - Global Host Control */
494     reg = ahci_rreg(ahci, AHCI_GHC);
495     ASSERT_BIT_CLEAR(reg, AHCI_GHC_HR);
496     ASSERT_BIT_CLEAR(reg, AHCI_GHC_IE);
497     ASSERT_BIT_CLEAR(reg, AHCI_GHC_MRSM);
498     if (BITSET(ahci->cap, AHCI_CAP_SAM)) {
499         g_test_message("Supports AHCI-Only Mode: GHC_AE is Read-Only.");
500         ASSERT_BIT_SET(reg, AHCI_GHC_AE);
501     } else {
502         g_test_message("Supports AHCI/Legacy mix.");
503         ASSERT_BIT_CLEAR(reg, AHCI_GHC_AE);
504     }
505
506     /* 3 IS - Interrupt Status */
507     reg = ahci_rreg(ahci, AHCI_IS);
508     g_assert_cmphex(reg, ==, 0);
509
510     /* 4 PI - Ports Implemented */
511     ports = ahci_rreg(ahci, AHCI_PI);
512     /* Ports Implemented must be non-zero. */
513     g_assert_cmphex(ports, !=, 0);
514     /* Ports Implemented must be <= Number of Ports. */
515     nports_impl = ctpopl(ports);
516     g_assert_cmpuint(((AHCI_CAP_NP & ahci->cap) + 1), >=, nports_impl);
517
518     /* Ports must be within the proper range. Given a mapping of SIZE,
519      * 256 bytes are used for global HBA control, and the rest is used
520      * for ports data, at 0x80 bytes each. */
521     g_assert_cmphex(ahci->barsize, >, 0);
522     maxports = (ahci->barsize - HBA_DATA_REGION_SIZE) / HBA_PORT_DATA_SIZE;
523     /* e.g, 30 ports for 4K of memory. (4096 - 256) / 128 = 30 */
524     g_assert_cmphex((reg >> maxports), ==, 0);
525
526     /* 5 AHCI Version */
527     reg = ahci_rreg(ahci, AHCI_VS);
528     switch (reg) {
529     case AHCI_VERSION_0_95:
530     case AHCI_VERSION_1_0:
531     case AHCI_VERSION_1_1:
532     case AHCI_VERSION_1_2:
533     case AHCI_VERSION_1_3:
534         break;
535     default:
536         g_assert_not_reached();
537     }
538
539     /* 6 Command Completion Coalescing Control: depends on CAP.CCCS. */
540     reg = ahci_rreg(ahci, AHCI_CCCCTL);
541     if (BITSET(ahci->cap, AHCI_CAP_CCCS)) {
542         ASSERT_BIT_CLEAR(reg, AHCI_CCCCTL_EN);
543         ASSERT_BIT_CLEAR(reg, AHCI_CCCCTL_RESERVED);
544         ASSERT_BIT_SET(reg, AHCI_CCCCTL_CC);
545         ASSERT_BIT_SET(reg, AHCI_CCCCTL_TV);
546     } else {
547         g_assert_cmphex(reg, ==, 0);
548     }
549
550     /* 7 CCC_PORTS */
551     reg = ahci_rreg(ahci, AHCI_CCCPORTS);
552     /* Must be zeroes initially regardless of CAP.CCCS */
553     g_assert_cmphex(reg, ==, 0);
554
555     /* 8 EM_LOC */
556     reg = ahci_rreg(ahci, AHCI_EMLOC);
557     if (BITCLR(ahci->cap, AHCI_CAP_EMS)) {
558         g_assert_cmphex(reg, ==, 0);
559     }
560
561     /* 9 EM_CTL */
562     reg = ahci_rreg(ahci, AHCI_EMCTL);
563     if (BITSET(ahci->cap, AHCI_CAP_EMS)) {
564         ASSERT_BIT_CLEAR(reg, AHCI_EMCTL_STSMR);
565         ASSERT_BIT_CLEAR(reg, AHCI_EMCTL_CTLTM);
566         ASSERT_BIT_CLEAR(reg, AHCI_EMCTL_CTLRST);
567         ASSERT_BIT_CLEAR(reg, AHCI_EMCTL_RESERVED);
568     } else {
569         g_assert_cmphex(reg, ==, 0);
570     }
571
572     /* 10 CAP2 -- Capabilities Extended */
573     ahci->cap2 = ahci_rreg(ahci, AHCI_CAP2);
574     ASSERT_BIT_CLEAR(ahci->cap2, AHCI_CAP2_RESERVED);
575
576     /* 11 BOHC -- Bios/OS Handoff Control */
577     reg = ahci_rreg(ahci, AHCI_BOHC);
578     g_assert_cmphex(reg, ==, 0);
579
580     /* 12 -- 23: Reserved */
581     g_test_message("Verifying HBA reserved area is empty.");
582     for (i = AHCI_RESERVED; i < AHCI_NVMHCI; ++i) {
583         reg = ahci_rreg(ahci, i);
584         g_assert_cmphex(reg, ==, 0);
585     }
586
587     /* 24 -- 39: NVMHCI */
588     if (BITCLR(ahci->cap2, AHCI_CAP2_NVMP)) {
589         g_test_message("Verifying HBA/NVMHCI area is empty.");
590         for (i = AHCI_NVMHCI; i < AHCI_VENDOR; ++i) {
591             reg = ahci_rreg(ahci, i);
592             g_assert_cmphex(reg, ==, 0);
593         }
594     }
595
596     /* 40 -- 63: Vendor */
597     g_test_message("Verifying HBA/Vendor area is empty.");
598     for (i = AHCI_VENDOR; i < AHCI_PORTS; ++i) {
599         reg = ahci_rreg(ahci, i);
600         g_assert_cmphex(reg, ==, 0);
601     }
602
603     /* 64 -- XX: Port Space */
604     for (i = 0; ports || (i < maxports); ports >>= 1, ++i) {
605         if (BITSET(ports, 0x1)) {
606             g_test_message("Testing port %u for spec", i);
607             ahci_test_port_spec(ahci, i);
608         } else {
609             uint16_t j;
610             uint16_t low = AHCI_PORTS + (32 * i);
611             uint16_t high = AHCI_PORTS + (32 * (i + 1));
612             g_test_message("Asserting unimplemented port %u "
613                            "(reg [%u-%u]) is empty.",
614                            i, low, high - 1);
615             for (j = low; j < high; ++j) {
616                 reg = ahci_rreg(ahci, j);
617                 g_assert_cmphex(reg, ==, 0);
618             }
619         }
620     }
621 }
622
623 /**
624  * Test the memory space for one port for specification adherence.
625  */
626 static void ahci_test_port_spec(AHCIQState *ahci, uint8_t port)
627 {
628     uint32_t reg;
629     unsigned i;
630
631     /* (0) CLB */
632     reg = ahci_px_rreg(ahci, port, AHCI_PX_CLB);
633     ASSERT_BIT_CLEAR(reg, AHCI_PX_CLB_RESERVED);
634
635     /* (1) CLBU */
636     if (BITCLR(ahci->cap, AHCI_CAP_S64A)) {
637         reg = ahci_px_rreg(ahci, port, AHCI_PX_CLBU);
638         g_assert_cmphex(reg, ==, 0);
639     }
640
641     /* (2) FB */
642     reg = ahci_px_rreg(ahci, port, AHCI_PX_FB);
643     ASSERT_BIT_CLEAR(reg, AHCI_PX_FB_RESERVED);
644
645     /* (3) FBU */
646     if (BITCLR(ahci->cap, AHCI_CAP_S64A)) {
647         reg = ahci_px_rreg(ahci, port, AHCI_PX_FBU);
648         g_assert_cmphex(reg, ==, 0);
649     }
650
651     /* (4) IS */
652     reg = ahci_px_rreg(ahci, port, AHCI_PX_IS);
653     g_assert_cmphex(reg, ==, 0);
654
655     /* (5) IE */
656     reg = ahci_px_rreg(ahci, port, AHCI_PX_IE);
657     g_assert_cmphex(reg, ==, 0);
658
659     /* (6) CMD */
660     reg = ahci_px_rreg(ahci, port, AHCI_PX_CMD);
661     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_FRE);
662     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_RESERVED);
663     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_CCS);
664     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_FR);
665     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_CR);
666     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_PMA); /* And RW only if CAP.SPM */
667     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_APSTE); /* RW only if CAP2.APST */
668     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_ATAPI);
669     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_DLAE);
670     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_ALPE);  /* RW only if CAP.SALP */
671     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_ASP);   /* RW only if CAP.SALP */
672     ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_ICC);
673     /* If CPDetect support does not exist, CPState must be off. */
674     if (BITCLR(reg, AHCI_PX_CMD_CPD)) {
675         ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_CPS);
676     }
677     /* If MPSPresence is not set, MPSState must be off. */
678     if (BITCLR(reg, AHCI_PX_CMD_MPSP)) {
679         ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_MPSS);
680     }
681     /* If we do not support MPS, MPSS and MPSP must be off. */
682     if (BITCLR(ahci->cap, AHCI_CAP_SMPS)) {
683         ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_MPSS);
684         ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_MPSP);
685     }
686     /* If, via CPD or MPSP we detect a drive, HPCP must be on. */
687     if (BITANY(reg, AHCI_PX_CMD_CPD | AHCI_PX_CMD_MPSP)) {
688         ASSERT_BIT_SET(reg, AHCI_PX_CMD_HPCP);
689     }
690     /* HPCP and ESP cannot both be active. */
691     g_assert(!BITSET(reg, AHCI_PX_CMD_HPCP | AHCI_PX_CMD_ESP));
692     /* If CAP.FBSS is not set, FBSCP must not be set. */
693     if (BITCLR(ahci->cap, AHCI_CAP_FBSS)) {
694         ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_FBSCP);
695     }
696
697     /* (7) RESERVED */
698     reg = ahci_px_rreg(ahci, port, AHCI_PX_RES1);
699     g_assert_cmphex(reg, ==, 0);
700
701     /* (8) TFD */
702     reg = ahci_px_rreg(ahci, port, AHCI_PX_TFD);
703     /* At boot, prior to an FIS being received, the TFD register should be 0x7F,
704      * which breaks down as follows, as seen in AHCI 1.3 sec 3.3.8, p. 27. */
705     ASSERT_BIT_SET(reg, AHCI_PX_TFD_STS_ERR);
706     ASSERT_BIT_SET(reg, AHCI_PX_TFD_STS_CS1);
707     ASSERT_BIT_SET(reg, AHCI_PX_TFD_STS_DRQ);
708     ASSERT_BIT_SET(reg, AHCI_PX_TFD_STS_CS2);
709     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_STS_BSY);
710     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_ERR);
711     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_RESERVED);
712
713     /* (9) SIG */
714     /* Though AHCI specifies the boot value should be 0xFFFFFFFF,
715      * Even when GHC.ST is zero, the AHCI HBA may receive the initial
716      * D2H register FIS and update the signature asynchronously,
717      * so we cannot expect a value here. AHCI 1.3, sec 3.3.9, pp 27-28 */
718
719     /* (10) SSTS / SCR0: SStatus */
720     reg = ahci_px_rreg(ahci, port, AHCI_PX_SSTS);
721     ASSERT_BIT_CLEAR(reg, AHCI_PX_SSTS_RESERVED);
722     /* Even though the register should be 0 at boot, it is asynchronous and
723      * prone to change, so we cannot test any well known value. */
724
725     /* (11) SCTL / SCR2: SControl */
726     reg = ahci_px_rreg(ahci, port, AHCI_PX_SCTL);
727     g_assert_cmphex(reg, ==, 0);
728
729     /* (12) SERR / SCR1: SError */
730     reg = ahci_px_rreg(ahci, port, AHCI_PX_SERR);
731     g_assert_cmphex(reg, ==, 0);
732
733     /* (13) SACT / SCR3: SActive */
734     reg = ahci_px_rreg(ahci, port, AHCI_PX_SACT);
735     g_assert_cmphex(reg, ==, 0);
736
737     /* (14) CI */
738     reg = ahci_px_rreg(ahci, port, AHCI_PX_CI);
739     g_assert_cmphex(reg, ==, 0);
740
741     /* (15) SNTF */
742     reg = ahci_px_rreg(ahci, port, AHCI_PX_SNTF);
743     g_assert_cmphex(reg, ==, 0);
744
745     /* (16) FBS */
746     reg = ahci_px_rreg(ahci, port, AHCI_PX_FBS);
747     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_EN);
748     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_DEC);
749     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_SDE);
750     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_DEV);
751     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_DWE);
752     ASSERT_BIT_CLEAR(reg, AHCI_PX_FBS_RESERVED);
753     if (BITSET(ahci->cap, AHCI_CAP_FBSS)) {
754         /* if Port-Multiplier FIS-based switching avail, ADO must >= 2 */
755         g_assert((reg & AHCI_PX_FBS_ADO) >> ctzl(AHCI_PX_FBS_ADO) >= 2);
756     }
757
758     /* [17 -- 27] RESERVED */
759     for (i = AHCI_PX_RES2; i < AHCI_PX_VS; ++i) {
760         reg = ahci_px_rreg(ahci, port, i);
761         g_assert_cmphex(reg, ==, 0);
762     }
763
764     /* [28 -- 31] Vendor-Specific */
765     for (i = AHCI_PX_VS; i < 32; ++i) {
766         reg = ahci_px_rreg(ahci, port, i);
767         if (reg) {
768             g_test_message("INFO: Vendor register %u non-empty", i);
769         }
770     }
771 }
772
773 /**
774  * Utilizing an initialized AHCI HBA, issue an IDENTIFY command to the first
775  * device we see, then read and check the response.
776  */
777 static void ahci_test_identify(AHCIQState *ahci)
778 {
779     uint16_t buff[256];
780     unsigned px;
781     int rc;
782     uint16_t sect_size;
783     const size_t buffsize = 512;
784
785     g_assert(ahci != NULL);
786
787     /**
788      * This serves as a bit of a tutorial on AHCI device programming:
789      *
790      * (1) Create a data buffer for the IDENTIFY response to be sent to
791      * (2) Create a Command Table buffer, where we will store the
792      *     command and PRDT (Physical Region Descriptor Table)
793      * (3) Construct an FIS host-to-device command structure, and write it to
794      *     the top of the Command Table buffer.
795      * (4) Create one or more Physical Region Descriptors (PRDs) that describe
796      *     a location in memory where data may be stored/retrieved.
797      * (5) Write these PRDTs to the bottom (offset 0x80) of the Command Table.
798      * (6) Each AHCI port has up to 32 command slots. Each slot contains a
799      *     header that points to a Command Table buffer. Pick an unused slot
800      *     and update it to point to the Command Table we have built.
801      * (7) Now: Command #n points to our Command Table, and our Command Table
802      *     contains the FIS (that describes our command) and the PRDTL, which
803      *     describes our buffer.
804      * (8) We inform the HBA via PxCI (Command Issue) that the command in slot
805      *     #n is ready for processing.
806      */
807
808     /* Pick the first implemented and running port */
809     px = ahci_port_select(ahci);
810     g_test_message("Selected port %u for test", px);
811
812     /* Clear out the FIS Receive area and any pending interrupts. */
813     ahci_port_clear(ahci, px);
814
815     /* "Read" 512 bytes using CMD_IDENTIFY into the host buffer. */
816     ahci_io(ahci, px, CMD_IDENTIFY, &buff, buffsize, 0);
817
818     /* Check serial number/version in the buffer */
819     /* NB: IDENTIFY strings are packed in 16bit little endian chunks.
820      * Since we copy byte-for-byte in ahci-test, on both LE and BE, we need to
821      * unchunk this data. By contrast, ide-test copies 2 bytes at a time, and
822      * as a consequence, only needs to unchunk the data on LE machines. */
823     string_bswap16(&buff[10], 20);
824     rc = memcmp(&buff[10], "testdisk            ", 20);
825     g_assert_cmphex(rc, ==, 0);
826
827     string_bswap16(&buff[23], 8);
828     rc = memcmp(&buff[23], "version ", 8);
829     g_assert_cmphex(rc, ==, 0);
830
831     sect_size = le16_to_cpu(*((uint16_t *)(&buff[5])));
832     g_assert_cmphex(sect_size, ==, AHCI_SECTOR_SIZE);
833 }
834
835 static void ahci_test_io_rw_simple(AHCIQState *ahci, unsigned bufsize,
836                                    uint64_t sector, uint8_t read_cmd,
837                                    uint8_t write_cmd)
838 {
839     uint64_t ptr;
840     uint8_t port;
841     unsigned char *tx = g_malloc(bufsize);
842     unsigned char *rx = g_malloc0(bufsize);
843
844     g_assert(ahci != NULL);
845
846     /* Pick the first running port and clear it. */
847     port = ahci_port_select(ahci);
848     ahci_port_clear(ahci, port);
849
850     /*** Create pattern and transfer to guest ***/
851     /* Data buffer in the guest */
852     ptr = ahci_alloc(ahci, bufsize);
853     g_assert(ptr);
854
855     /* Write some indicative pattern to our buffer. */
856     generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
857     bufwrite(ptr, tx, bufsize);
858
859     /* Write this buffer to disk, then read it back to the DMA buffer. */
860     ahci_guest_io(ahci, port, write_cmd, ptr, bufsize, sector);
861     qmemset(ptr, 0x00, bufsize);
862     ahci_guest_io(ahci, port, read_cmd, ptr, bufsize, sector);
863
864     /*** Read back the Data ***/
865     bufread(ptr, rx, bufsize);
866     g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);
867
868     ahci_free(ahci, ptr);
869     g_free(tx);
870     g_free(rx);
871 }
872
873 static uint8_t ahci_test_nondata(AHCIQState *ahci, uint8_t ide_cmd)
874 {
875     uint8_t port;
876     AHCICommand *cmd;
877
878     /* Sanitize */
879     port = ahci_port_select(ahci);
880     ahci_port_clear(ahci, port);
881
882     /* Issue Command */
883     cmd = ahci_command_create(ide_cmd);
884     ahci_command_commit(ahci, cmd, port);
885     ahci_command_issue(ahci, cmd);
886     ahci_command_verify(ahci, cmd);
887     ahci_command_free(cmd);
888
889     return port;
890 }
891
892 static void ahci_test_flush(AHCIQState *ahci)
893 {
894     ahci_test_nondata(ahci, CMD_FLUSH_CACHE);
895 }
896
897 static void ahci_test_max(AHCIQState *ahci)
898 {
899     RegD2HFIS *d2h = g_malloc0(0x20);
900     uint64_t nsect;
901     uint8_t port;
902     uint8_t cmd;
903     uint64_t config_sect = TEST_IMAGE_SECTORS - 1;
904
905     if (config_sect > 0xFFFFFF) {
906         cmd = CMD_READ_MAX_EXT;
907     } else {
908         cmd = CMD_READ_MAX;
909     }
910
911     port = ahci_test_nondata(ahci, cmd);
912     memread(ahci->port[port].fb + 0x40, d2h, 0x20);
913     nsect = (uint64_t)d2h->lba_hi[2] << 40 |
914         (uint64_t)d2h->lba_hi[1] << 32 |
915         (uint64_t)d2h->lba_hi[0] << 24 |
916         (uint64_t)d2h->lba_lo[2] << 16 |
917         (uint64_t)d2h->lba_lo[1] << 8 |
918         (uint64_t)d2h->lba_lo[0];
919
920     g_assert_cmphex(nsect, ==, config_sect);
921     g_free(d2h);
922 }
923
924
925 /******************************************************************************/
926 /* Test Interfaces                                                            */
927 /******************************************************************************/
928
929 /**
930  * Basic sanity test to boot a machine, find an AHCI device, and shutdown.
931  */
932 static void test_sanity(void)
933 {
934     AHCIQState *ahci;
935     ahci = ahci_boot(NULL);
936     ahci_shutdown(ahci);
937 }
938
939 /**
940  * Ensure that the PCI configuration space for the AHCI device is in-line with
941  * the AHCI 1.3 specification for initial values.
942  */
943 static void test_pci_spec(void)
944 {
945     AHCIQState *ahci;
946     ahci = ahci_boot(NULL);
947     ahci_test_pci_spec(ahci);
948     ahci_shutdown(ahci);
949 }
950
951 /**
952  * Engage the PCI AHCI device and sanity check the response.
953  * Perform additional PCI config space bringup for the HBA.
954  */
955 static void test_pci_enable(void)
956 {
957     AHCIQState *ahci;
958     ahci = ahci_boot(NULL);
959     ahci_pci_enable(ahci);
960     ahci_shutdown(ahci);
961 }
962
963 /**
964  * Investigate the memory mapped regions of the HBA,
965  * and test them for AHCI specification adherence.
966  */
967 static void test_hba_spec(void)
968 {
969     AHCIQState *ahci;
970
971     ahci = ahci_boot(NULL);
972     ahci_pci_enable(ahci);
973     ahci_test_hba_spec(ahci);
974     ahci_shutdown(ahci);
975 }
976
977 /**
978  * Engage the HBA functionality of the AHCI PCI device,
979  * and bring it into a functional idle state.
980  */
981 static void test_hba_enable(void)
982 {
983     AHCIQState *ahci;
984
985     ahci = ahci_boot(NULL);
986     ahci_pci_enable(ahci);
987     ahci_hba_enable(ahci);
988     ahci_shutdown(ahci);
989 }
990
991 /**
992  * Bring up the device and issue an IDENTIFY command.
993  * Inspect the state of the HBA device and the data returned.
994  */
995 static void test_identify(void)
996 {
997     AHCIQState *ahci;
998
999     ahci = ahci_boot_and_enable(NULL);
1000     ahci_test_identify(ahci);
1001     ahci_shutdown(ahci);
1002 }
1003
1004 /**
1005  * Fragmented DMA test: Perform a standard 4K DMA read/write
1006  * test, but make sure the physical regions are fragmented to
1007  * be very small, each just 32 bytes, to see how AHCI performs
1008  * with chunks defined to be much less than a sector.
1009  */
1010 static void test_dma_fragmented(void)
1011 {
1012     AHCIQState *ahci;
1013     AHCICommand *cmd;
1014     uint8_t px;
1015     size_t bufsize = 4096;
1016     unsigned char *tx = g_malloc(bufsize);
1017     unsigned char *rx = g_malloc0(bufsize);
1018     uint64_t ptr;
1019
1020     ahci = ahci_boot_and_enable(NULL);
1021     px = ahci_port_select(ahci);
1022     ahci_port_clear(ahci, px);
1023
1024     /* create pattern */
1025     generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
1026
1027     /* Create a DMA buffer in guest memory, and write our pattern to it. */
1028     ptr = guest_alloc(ahci->parent->alloc, bufsize);
1029     g_assert(ptr);
1030     bufwrite(ptr, tx, bufsize);
1031
1032     cmd = ahci_command_create(CMD_WRITE_DMA);
1033     ahci_command_adjust(cmd, 0, ptr, bufsize, 32);
1034     ahci_command_commit(ahci, cmd, px);
1035     ahci_command_issue(ahci, cmd);
1036     ahci_command_verify(ahci, cmd);
1037     g_free(cmd);
1038
1039     cmd = ahci_command_create(CMD_READ_DMA);
1040     ahci_command_adjust(cmd, 0, ptr, bufsize, 32);
1041     ahci_command_commit(ahci, cmd, px);
1042     ahci_command_issue(ahci, cmd);
1043     ahci_command_verify(ahci, cmd);
1044     g_free(cmd);
1045
1046     /* Read back the guest's receive buffer into local memory */
1047     bufread(ptr, rx, bufsize);
1048     guest_free(ahci->parent->alloc, ptr);
1049
1050     g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);
1051
1052     ahci_shutdown(ahci);
1053
1054     g_free(rx);
1055     g_free(tx);
1056 }
1057
1058 static void test_flush(void)
1059 {
1060     AHCIQState *ahci;
1061
1062     ahci = ahci_boot_and_enable(NULL);
1063     ahci_test_flush(ahci);
1064     ahci_shutdown(ahci);
1065 }
1066
1067 static void test_flush_retry(void)
1068 {
1069     AHCIQState *ahci;
1070     AHCICommand *cmd;
1071     uint8_t port;
1072     const char *s;
1073
1074     prepare_blkdebug_script(debug_path, "flush_to_disk");
1075     ahci = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
1076                                 "format=qcow2,cache=writeback,"
1077                                 "rerror=stop,werror=stop "
1078                                 "-M q35 "
1079                                 "-device ide-hd,drive=drive0 ",
1080                                 debug_path,
1081                                 tmp_path);
1082
1083     /* Issue Flush Command and wait for error */
1084     port = ahci_port_select(ahci);
1085     ahci_port_clear(ahci, port);
1086     cmd = ahci_command_create(CMD_FLUSH_CACHE);
1087     ahci_command_commit(ahci, cmd, port);
1088     ahci_command_issue_async(ahci, cmd);
1089     qmp_eventwait("STOP");
1090
1091     /* Complete the command */
1092     s = "{'execute':'cont' }";
1093     qmp_async(s);
1094     qmp_eventwait("RESUME");
1095     ahci_command_wait(ahci, cmd);
1096     ahci_command_verify(ahci, cmd);
1097
1098     ahci_command_free(cmd);
1099     ahci_shutdown(ahci);
1100 }
1101
1102 /**
1103  * Basic sanity test to boot a machine, find an AHCI device, and shutdown.
1104  */
1105 static void test_migrate_sanity(void)
1106 {
1107     AHCIQState *src, *dst;
1108     const char *uri = "tcp:127.0.0.1:1234";
1109
1110     src = ahci_boot("-m 1024 -M q35 "
1111                     "-hda %s ", tmp_path);
1112     dst = ahci_boot("-m 1024 -M q35 "
1113                     "-hda %s "
1114                     "-incoming %s", tmp_path, uri);
1115
1116     ahci_migrate(src, dst, uri);
1117
1118     ahci_shutdown(src);
1119     ahci_shutdown(dst);
1120 }
1121
1122 /**
1123  * Simple migration test: Write a pattern, migrate, then read.
1124  */
1125 static void ahci_migrate_simple(uint8_t cmd_read, uint8_t cmd_write)
1126 {
1127     AHCIQState *src, *dst;
1128     uint8_t px;
1129     size_t bufsize = 4096;
1130     unsigned char *tx = g_malloc(bufsize);
1131     unsigned char *rx = g_malloc0(bufsize);
1132     const char *uri = "tcp:127.0.0.1:1234";
1133
1134     src = ahci_boot_and_enable("-m 1024 -M q35 "
1135                                "-hda %s ", tmp_path);
1136     dst = ahci_boot("-m 1024 -M q35 "
1137                     "-hda %s "
1138                     "-incoming %s", tmp_path, uri);
1139
1140     set_context(src->parent);
1141
1142     /* initialize */
1143     px = ahci_port_select(src);
1144     ahci_port_clear(src, px);
1145
1146     /* create pattern */
1147     generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
1148
1149     /* Write, migrate, then read. */
1150     ahci_io(src, px, cmd_write, tx, bufsize, 0);
1151     ahci_migrate(src, dst, uri);
1152     ahci_io(dst, px, cmd_read, rx, bufsize, 0);
1153
1154     /* Verify pattern */
1155     g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);
1156
1157     ahci_shutdown(src);
1158     ahci_shutdown(dst);
1159     g_free(rx);
1160     g_free(tx);
1161 }
1162
1163 static void test_migrate_dma(void)
1164 {
1165     ahci_migrate_simple(CMD_READ_DMA, CMD_WRITE_DMA);
1166 }
1167
1168 static void test_migrate_ncq(void)
1169 {
1170     ahci_migrate_simple(READ_FPDMA_QUEUED, WRITE_FPDMA_QUEUED);
1171 }
1172
1173 /**
1174  * Halted IO Error Test
1175  *
1176  * Simulate an error on first write, Try to write a pattern,
1177  * Confirm the VM has stopped, resume the VM, verify command
1178  * has completed, then read back the data and verify.
1179  */
1180 static void ahci_halted_io_test(uint8_t cmd_read, uint8_t cmd_write)
1181 {
1182     AHCIQState *ahci;
1183     uint8_t port;
1184     size_t bufsize = 4096;
1185     unsigned char *tx = g_malloc(bufsize);
1186     unsigned char *rx = g_malloc0(bufsize);
1187     uint64_t ptr;
1188     AHCICommand *cmd;
1189
1190     prepare_blkdebug_script(debug_path, "write_aio");
1191
1192     ahci = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
1193                                 "format=qcow2,cache=writeback,"
1194                                 "rerror=stop,werror=stop "
1195                                 "-M q35 "
1196                                 "-device ide-hd,drive=drive0 ",
1197                                 debug_path,
1198                                 tmp_path);
1199
1200     /* Initialize and prepare */
1201     port = ahci_port_select(ahci);
1202     ahci_port_clear(ahci, port);
1203
1204     /* create DMA source buffer and write pattern */
1205     generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
1206     ptr = ahci_alloc(ahci, bufsize);
1207     g_assert(ptr);
1208     memwrite(ptr, tx, bufsize);
1209
1210     /* Attempt to write (and fail) */
1211     cmd = ahci_guest_io_halt(ahci, port, cmd_write,
1212                              ptr, bufsize, 0);
1213
1214     /* Attempt to resume the command */
1215     ahci_guest_io_resume(ahci, cmd);
1216     ahci_free(ahci, ptr);
1217
1218     /* Read back and verify */
1219     ahci_io(ahci, port, cmd_read, rx, bufsize, 0);
1220     g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);
1221
1222     /* Cleanup and go home */
1223     ahci_shutdown(ahci);
1224     g_free(rx);
1225     g_free(tx);
1226 }
1227
1228 static void test_halted_dma(void)
1229 {
1230     ahci_halted_io_test(CMD_READ_DMA, CMD_WRITE_DMA);
1231 }
1232
1233 static void test_halted_ncq(void)
1234 {
1235     ahci_halted_io_test(READ_FPDMA_QUEUED, WRITE_FPDMA_QUEUED);
1236 }
1237
1238 /**
1239  * IO Error Migration Test
1240  *
1241  * Simulate an error on first write, Try to write a pattern,
1242  * Confirm the VM has stopped, migrate, resume the VM,
1243  * verify command has completed, then read back the data and verify.
1244  */
1245 static void ahci_migrate_halted_io(uint8_t cmd_read, uint8_t cmd_write)
1246 {
1247     AHCIQState *src, *dst;
1248     uint8_t port;
1249     size_t bufsize = 4096;
1250     unsigned char *tx = g_malloc(bufsize);
1251     unsigned char *rx = g_malloc0(bufsize);
1252     uint64_t ptr;
1253     AHCICommand *cmd;
1254     const char *uri = "tcp:127.0.0.1:1234";
1255
1256     prepare_blkdebug_script(debug_path, "write_aio");
1257
1258     src = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
1259                                "format=qcow2,cache=writeback,"
1260                                "rerror=stop,werror=stop "
1261                                "-M q35 "
1262                                "-device ide-hd,drive=drive0 ",
1263                                debug_path,
1264                                tmp_path);
1265
1266     dst = ahci_boot("-drive file=%s,if=none,id=drive0,"
1267                     "format=qcow2,cache=writeback,"
1268                     "rerror=stop,werror=stop "
1269                     "-M q35 "
1270                     "-device ide-hd,drive=drive0 "
1271                     "-incoming %s",
1272                     tmp_path, uri);
1273
1274     set_context(src->parent);
1275
1276     /* Initialize and prepare */
1277     port = ahci_port_select(src);
1278     ahci_port_clear(src, port);
1279     generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
1280
1281     /* create DMA source buffer and write pattern */
1282     ptr = ahci_alloc(src, bufsize);
1283     g_assert(ptr);
1284     memwrite(ptr, tx, bufsize);
1285
1286     /* Write, trigger the VM to stop, migrate, then resume. */
1287     cmd = ahci_guest_io_halt(src, port, cmd_write,
1288                              ptr, bufsize, 0);
1289     ahci_migrate(src, dst, uri);
1290     ahci_guest_io_resume(dst, cmd);
1291     ahci_free(dst, ptr);
1292
1293     /* Read back */
1294     ahci_io(dst, port, cmd_read, rx, bufsize, 0);
1295
1296     /* Verify TX and RX are identical */
1297     g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);
1298
1299     /* Cleanup and go home. */
1300     ahci_shutdown(src);
1301     ahci_shutdown(dst);
1302     g_free(rx);
1303     g_free(tx);
1304 }
1305
1306 static void test_migrate_halted_dma(void)
1307 {
1308     ahci_migrate_halted_io(CMD_READ_DMA, CMD_WRITE_DMA);
1309 }
1310
1311 static void test_migrate_halted_ncq(void)
1312 {
1313     ahci_migrate_halted_io(READ_FPDMA_QUEUED, WRITE_FPDMA_QUEUED);
1314 }
1315
1316 /**
1317  * Migration test: Try to flush, migrate, then resume.
1318  */
1319 static void test_flush_migrate(void)
1320 {
1321     AHCIQState *src, *dst;
1322     AHCICommand *cmd;
1323     uint8_t px;
1324     const char *s;
1325     const char *uri = "tcp:127.0.0.1:1234";
1326
1327     prepare_blkdebug_script(debug_path, "flush_to_disk");
1328
1329     src = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
1330                                "cache=writeback,rerror=stop,werror=stop "
1331                                "-M q35 "
1332                                "-device ide-hd,drive=drive0 ",
1333                                debug_path, tmp_path);
1334     dst = ahci_boot("-drive file=%s,if=none,id=drive0,"
1335                     "cache=writeback,rerror=stop,werror=stop "
1336                     "-M q35 "
1337                     "-device ide-hd,drive=drive0 "
1338                     "-incoming %s", tmp_path, uri);
1339
1340     set_context(src->parent);
1341
1342     /* Issue Flush Command */
1343     px = ahci_port_select(src);
1344     ahci_port_clear(src, px);
1345     cmd = ahci_command_create(CMD_FLUSH_CACHE);
1346     ahci_command_commit(src, cmd, px);
1347     ahci_command_issue_async(src, cmd);
1348     qmp_eventwait("STOP");
1349
1350     /* Migrate over */
1351     ahci_migrate(src, dst, uri);
1352
1353     /* Complete the command */
1354     s = "{'execute':'cont' }";
1355     qmp_async(s);
1356     qmp_eventwait("RESUME");
1357     ahci_command_wait(dst, cmd);
1358     ahci_command_verify(dst, cmd);
1359
1360     ahci_command_free(cmd);
1361     ahci_shutdown(src);
1362     ahci_shutdown(dst);
1363 }
1364
1365 static void test_max(void)
1366 {
1367     AHCIQState *ahci;
1368
1369     ahci = ahci_boot_and_enable(NULL);
1370     ahci_test_max(ahci);
1371     ahci_shutdown(ahci);
1372 }
1373
1374 static void test_reset(void)
1375 {
1376     AHCIQState *ahci;
1377     int i;
1378
1379     ahci = ahci_boot(NULL);
1380     ahci_test_pci_spec(ahci);
1381     ahci_pci_enable(ahci);
1382
1383     for (i = 0; i < 2; i++) {
1384         ahci_test_hba_spec(ahci);
1385         ahci_hba_enable(ahci);
1386         ahci_test_identify(ahci);
1387         ahci_test_io_rw_simple(ahci, 4096, 0,
1388                                CMD_READ_DMA_EXT,
1389                                CMD_WRITE_DMA_EXT);
1390         ahci_set(ahci, AHCI_GHC, AHCI_GHC_HR);
1391         ahci_clean_mem(ahci);
1392     }
1393
1394     ahci_shutdown(ahci);
1395 }
1396
1397 static void test_ncq_simple(void)
1398 {
1399     AHCIQState *ahci;
1400
1401     ahci = ahci_boot_and_enable(NULL);
1402     ahci_test_io_rw_simple(ahci, 4096, 0,
1403                            READ_FPDMA_QUEUED,
1404                            WRITE_FPDMA_QUEUED);
1405     ahci_shutdown(ahci);
1406 }
1407
1408 /******************************************************************************/
1409 /* AHCI I/O Test Matrix Definitions                                           */
1410
1411 enum BuffLen {
1412     LEN_BEGIN = 0,
1413     LEN_SIMPLE = LEN_BEGIN,
1414     LEN_DOUBLE,
1415     LEN_LONG,
1416     LEN_SHORT,
1417     NUM_LENGTHS
1418 };
1419
1420 static const char *buff_len_str[NUM_LENGTHS] = { "simple", "double",
1421                                                  "long", "short" };
1422
1423 enum AddrMode {
1424     ADDR_MODE_BEGIN = 0,
1425     ADDR_MODE_LBA28 = ADDR_MODE_BEGIN,
1426     ADDR_MODE_LBA48,
1427     NUM_ADDR_MODES
1428 };
1429
1430 static const char *addr_mode_str[NUM_ADDR_MODES] = { "lba28", "lba48" };
1431
1432 enum IOMode {
1433     MODE_BEGIN = 0,
1434     MODE_PIO = MODE_BEGIN,
1435     MODE_DMA,
1436     NUM_MODES
1437 };
1438
1439 static const char *io_mode_str[NUM_MODES] = { "pio", "dma" };
1440
1441 enum IOOps {
1442     IO_BEGIN = 0,
1443     IO_READ = IO_BEGIN,
1444     IO_WRITE,
1445     NUM_IO_OPS
1446 };
1447
1448 enum OffsetType {
1449     OFFSET_BEGIN = 0,
1450     OFFSET_ZERO = OFFSET_BEGIN,
1451     OFFSET_LOW,
1452     OFFSET_HIGH,
1453     NUM_OFFSETS
1454 };
1455
1456 static const char *offset_str[NUM_OFFSETS] = { "zero", "low", "high" };
1457
1458 typedef struct AHCIIOTestOptions {
1459     enum BuffLen length;
1460     enum AddrMode address_type;
1461     enum IOMode io_type;
1462     enum OffsetType offset;
1463 } AHCIIOTestOptions;
1464
1465 static uint64_t offset_sector(enum OffsetType ofst,
1466                               enum AddrMode addr_type,
1467                               uint64_t buffsize)
1468 {
1469     uint64_t ceil;
1470     uint64_t nsectors;
1471
1472     switch (ofst) {
1473     case OFFSET_ZERO:
1474         return 0;
1475     case OFFSET_LOW:
1476         return 1;
1477     case OFFSET_HIGH:
1478         ceil = (addr_type == ADDR_MODE_LBA28) ? 0xfffffff : 0xffffffffffff;
1479         ceil = MIN(ceil, TEST_IMAGE_SECTORS - 1);
1480         nsectors = buffsize / AHCI_SECTOR_SIZE;
1481         return ceil - nsectors + 1;
1482     default:
1483         g_assert_not_reached();
1484     }
1485 }
1486
1487 /**
1488  * Table of possible I/O ATA commands given a set of enumerations.
1489  */
1490 static const uint8_t io_cmds[NUM_MODES][NUM_ADDR_MODES][NUM_IO_OPS] = {
1491     [MODE_PIO] = {
1492         [ADDR_MODE_LBA28] = {
1493             [IO_READ] = CMD_READ_PIO,
1494             [IO_WRITE] = CMD_WRITE_PIO },
1495         [ADDR_MODE_LBA48] = {
1496             [IO_READ] = CMD_READ_PIO_EXT,
1497             [IO_WRITE] = CMD_WRITE_PIO_EXT }
1498     },
1499     [MODE_DMA] = {
1500         [ADDR_MODE_LBA28] = {
1501             [IO_READ] = CMD_READ_DMA,
1502             [IO_WRITE] = CMD_WRITE_DMA },
1503         [ADDR_MODE_LBA48] = {
1504             [IO_READ] = CMD_READ_DMA_EXT,
1505             [IO_WRITE] = CMD_WRITE_DMA_EXT }
1506     }
1507 };
1508
1509 /**
1510  * Test a Read/Write pattern using various commands, addressing modes,
1511  * transfer modes, and buffer sizes.
1512  */
1513 static void test_io_rw_interface(enum AddrMode lba48, enum IOMode dma,
1514                                  unsigned bufsize, uint64_t sector)
1515 {
1516     AHCIQState *ahci;
1517
1518     ahci = ahci_boot_and_enable(NULL);
1519     ahci_test_io_rw_simple(ahci, bufsize, sector,
1520                            io_cmds[dma][lba48][IO_READ],
1521                            io_cmds[dma][lba48][IO_WRITE]);
1522     ahci_shutdown(ahci);
1523 }
1524
1525 /**
1526  * Demultiplex the test data and invoke the actual test routine.
1527  */
1528 static void test_io_interface(gconstpointer opaque)
1529 {
1530     AHCIIOTestOptions *opts = (AHCIIOTestOptions *)opaque;
1531     unsigned bufsize;
1532     uint64_t sector;
1533
1534     switch (opts->length) {
1535     case LEN_SIMPLE:
1536         bufsize = 4096;
1537         break;
1538     case LEN_DOUBLE:
1539         bufsize = 8192;
1540         break;
1541     case LEN_LONG:
1542         bufsize = 4096 * 64;
1543         break;
1544     case LEN_SHORT:
1545         bufsize = 512;
1546         break;
1547     default:
1548         g_assert_not_reached();
1549     }
1550
1551     sector = offset_sector(opts->offset, opts->address_type, bufsize);
1552     test_io_rw_interface(opts->address_type, opts->io_type, bufsize, sector);
1553     g_free(opts);
1554     return;
1555 }
1556
1557 static void create_ahci_io_test(enum IOMode type, enum AddrMode addr,
1558                                 enum BuffLen len, enum OffsetType offset)
1559 {
1560     char *name;
1561     AHCIIOTestOptions *opts = g_malloc(sizeof(AHCIIOTestOptions));
1562
1563     opts->length = len;
1564     opts->address_type = addr;
1565     opts->io_type = type;
1566     opts->offset = offset;
1567
1568     name = g_strdup_printf("ahci/io/%s/%s/%s/%s",
1569                            io_mode_str[type],
1570                            addr_mode_str[addr],
1571                            buff_len_str[len],
1572                            offset_str[offset]);
1573
1574     qtest_add_data_func(name, opts, test_io_interface);
1575     g_free(name);
1576 }
1577
1578 /******************************************************************************/
1579
1580 int main(int argc, char **argv)
1581 {
1582     const char *arch;
1583     int ret;
1584     int fd;
1585     int c;
1586     int i, j, k, m;
1587
1588     static struct option long_options[] = {
1589         {"pedantic", no_argument, 0, 'p' },
1590         {0, 0, 0, 0},
1591     };
1592
1593     /* Should be first to utilize g_test functionality, So we can see errors. */
1594     g_test_init(&argc, &argv, NULL);
1595
1596     while (1) {
1597         c = getopt_long(argc, argv, "", long_options, NULL);
1598         if (c == -1) {
1599             break;
1600         }
1601         switch (c) {
1602         case -1:
1603             break;
1604         case 'p':
1605             ahci_pedantic = 1;
1606             break;
1607         default:
1608             fprintf(stderr, "Unrecognized ahci_test option.\n");
1609             g_assert_not_reached();
1610         }
1611     }
1612
1613     /* Check architecture */
1614     arch = qtest_get_arch();
1615     if (strcmp(arch, "i386") && strcmp(arch, "x86_64")) {
1616         g_test_message("Skipping test for non-x86");
1617         return 0;
1618     }
1619
1620     /* Create a temporary qcow2 image */
1621     close(mkstemp(tmp_path));
1622     mkqcow2(tmp_path, TEST_IMAGE_SIZE_MB);
1623
1624     /* Create temporary blkdebug instructions */
1625     fd = mkstemp(debug_path);
1626     g_assert(fd >= 0);
1627     close(fd);
1628
1629     /* Run the tests */
1630     qtest_add_func("/ahci/sanity",     test_sanity);
1631     qtest_add_func("/ahci/pci_spec",   test_pci_spec);
1632     qtest_add_func("/ahci/pci_enable", test_pci_enable);
1633     qtest_add_func("/ahci/hba_spec",   test_hba_spec);
1634     qtest_add_func("/ahci/hba_enable", test_hba_enable);
1635     qtest_add_func("/ahci/identify",   test_identify);
1636
1637     for (i = MODE_BEGIN; i < NUM_MODES; i++) {
1638         for (j = ADDR_MODE_BEGIN; j < NUM_ADDR_MODES; j++) {
1639             for (k = LEN_BEGIN; k < NUM_LENGTHS; k++) {
1640                 for (m = OFFSET_BEGIN; m < NUM_OFFSETS; m++) {
1641                     create_ahci_io_test(i, j, k, m);
1642                 }
1643             }
1644         }
1645     }
1646
1647     qtest_add_func("/ahci/io/dma/lba28/fragmented", test_dma_fragmented);
1648
1649     qtest_add_func("/ahci/flush/simple", test_flush);
1650     qtest_add_func("/ahci/flush/retry", test_flush_retry);
1651     qtest_add_func("/ahci/flush/migrate", test_flush_migrate);
1652
1653     qtest_add_func("/ahci/migrate/sanity", test_migrate_sanity);
1654     qtest_add_func("/ahci/migrate/dma/simple", test_migrate_dma);
1655     qtest_add_func("/ahci/io/dma/lba28/retry", test_halted_dma);
1656     qtest_add_func("/ahci/migrate/dma/halted", test_migrate_halted_dma);
1657
1658     qtest_add_func("/ahci/max", test_max);
1659     qtest_add_func("/ahci/reset", test_reset);
1660
1661     qtest_add_func("/ahci/io/ncq/simple", test_ncq_simple);
1662     qtest_add_func("/ahci/migrate/ncq/simple", test_migrate_ncq);
1663     qtest_add_func("/ahci/io/ncq/retry", test_halted_ncq);
1664     qtest_add_func("/ahci/migrate/ncq/halted", test_migrate_halted_ncq);
1665
1666     ret = g_test_run();
1667
1668     /* Cleanup */
1669     unlink(tmp_path);
1670     unlink(debug_path);
1671
1672     return ret;
1673 }
This page took 0.115931 seconds and 4 git commands to generate.