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