These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / tests / libqos / ahci.c
1 /*
2  * libqos AHCI functions
3  *
4  * Copyright (c) 2014 John Snow <jsnow@redhat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24
25 #include "qemu/osdep.h"
26 #include <glib.h>
27
28 #include "libqtest.h"
29 #include "libqos/ahci.h"
30 #include "libqos/pci-pc.h"
31
32 #include "qemu-common.h"
33 #include "qemu/host-utils.h"
34
35 #include "hw/pci/pci_ids.h"
36 #include "hw/pci/pci_regs.h"
37
38 typedef struct AHCICommandProp {
39     uint8_t  cmd;        /* Command Code */
40     bool     data;       /* Data transfer command? */
41     bool     pio;
42     bool     dma;
43     bool     lba28;
44     bool     lba48;
45     bool     read;
46     bool     write;
47     bool     atapi;
48     bool     ncq;
49     uint64_t size;       /* Static transfer size, for commands like IDENTIFY. */
50     uint32_t interrupts; /* Expected interrupts for this command. */
51 } AHCICommandProp;
52
53 AHCICommandProp ahci_command_properties[] = {
54     { .cmd = CMD_READ_PIO,       .data = true,  .pio = true,
55                                  .lba28 = true, .read = true },
56     { .cmd = CMD_WRITE_PIO,      .data = true,  .pio = true,
57                                  .lba28 = true, .write = true },
58     { .cmd = CMD_READ_PIO_EXT,   .data = true,  .pio = true,
59                                  .lba48 = true, .read = true },
60     { .cmd = CMD_WRITE_PIO_EXT,  .data = true,  .pio = true,
61                                  .lba48 = true, .write = true },
62     { .cmd = CMD_READ_DMA,       .data = true,  .dma = true,
63                                  .lba28 = true, .read = true },
64     { .cmd = CMD_WRITE_DMA,      .data = true,  .dma = true,
65                                  .lba28 = true, .write = true },
66     { .cmd = CMD_READ_DMA_EXT,   .data = true,  .dma = true,
67                                  .lba48 = true, .read = true },
68     { .cmd = CMD_WRITE_DMA_EXT,  .data = true,  .dma = true,
69                                  .lba48 = true, .write = true },
70     { .cmd = CMD_IDENTIFY,       .data = true,  .pio = true,
71                                  .size = 512,   .read = true },
72     { .cmd = READ_FPDMA_QUEUED,  .data = true,  .dma = true,
73                                  .lba48 = true, .read = true, .ncq = true },
74     { .cmd = WRITE_FPDMA_QUEUED, .data = true,  .dma = true,
75                                  .lba48 = true, .write = true, .ncq = true },
76     { .cmd = CMD_READ_MAX,       .lba28 = true },
77     { .cmd = CMD_READ_MAX_EXT,   .lba48 = true },
78     { .cmd = CMD_FLUSH_CACHE,    .data = false },
79     { .cmd = CMD_PACKET,         .data = true,  .size = 16,
80                                  .atapi = true, .pio = true },
81     { .cmd = CMD_PACKET_ID,      .data = true,  .pio = true,
82                                  .size = 512,   .read = true }
83 };
84
85 struct AHCICommand {
86     /* Test Management Data */
87     uint8_t name;
88     uint8_t port;
89     uint8_t slot;
90     uint32_t interrupts;
91     uint64_t xbytes;
92     uint32_t prd_size;
93     uint64_t buffer;
94     AHCICommandProp *props;
95     /* Data to be transferred to the guest */
96     AHCICommandHeader header;
97     RegH2DFIS fis;
98     unsigned char *atapi_cmd;
99 };
100
101 /**
102  * Allocate space in the guest using information in the AHCIQState object.
103  */
104 uint64_t ahci_alloc(AHCIQState *ahci, size_t bytes)
105 {
106     g_assert(ahci);
107     g_assert(ahci->parent);
108     return qmalloc(ahci->parent, bytes);
109 }
110
111 void ahci_free(AHCIQState *ahci, uint64_t addr)
112 {
113     g_assert(ahci);
114     g_assert(ahci->parent);
115     qfree(ahci->parent, addr);
116 }
117
118 bool is_atapi(AHCIQState *ahci, uint8_t port)
119 {
120     return ahci_px_rreg(ahci, port, AHCI_PX_SIG) == AHCI_SIGNATURE_CDROM;
121 }
122
123 /**
124  * Locate, verify, and return a handle to the AHCI device.
125  */
126 QPCIDevice *get_ahci_device(uint32_t *fingerprint)
127 {
128     QPCIDevice *ahci;
129     uint32_t ahci_fingerprint;
130     QPCIBus *pcibus;
131
132     pcibus = qpci_init_pc();
133
134     /* Find the AHCI PCI device and verify it's the right one. */
135     ahci = qpci_device_find(pcibus, QPCI_DEVFN(0x1F, 0x02));
136     g_assert(ahci != NULL);
137
138     ahci_fingerprint = qpci_config_readl(ahci, PCI_VENDOR_ID);
139
140     switch (ahci_fingerprint) {
141     case AHCI_INTEL_ICH9:
142         break;
143     default:
144         /* Unknown device. */
145         g_assert_not_reached();
146     }
147
148     if (fingerprint) {
149         *fingerprint = ahci_fingerprint;
150     }
151     return ahci;
152 }
153
154 void free_ahci_device(QPCIDevice *dev)
155 {
156     QPCIBus *pcibus = dev ? dev->bus : NULL;
157
158     /* libqos doesn't have a function for this, so free it manually */
159     g_free(dev);
160     qpci_free_pc(pcibus);
161 }
162
163 /* Free all memory in-use by the AHCI device. */
164 void ahci_clean_mem(AHCIQState *ahci)
165 {
166     uint8_t port, slot;
167
168     for (port = 0; port < 32; ++port) {
169         if (ahci->port[port].fb) {
170             ahci_free(ahci, ahci->port[port].fb);
171             ahci->port[port].fb = 0;
172         }
173         if (ahci->port[port].clb) {
174             for (slot = 0; slot < 32; slot++) {
175                 ahci_destroy_command(ahci, port, slot);
176             }
177             ahci_free(ahci, ahci->port[port].clb);
178             ahci->port[port].clb = 0;
179         }
180     }
181 }
182
183 /*** Logical Device Initialization ***/
184
185 /**
186  * Start the PCI device and sanity-check default operation.
187  */
188 void ahci_pci_enable(AHCIQState *ahci)
189 {
190     uint8_t reg;
191
192     start_ahci_device(ahci);
193
194     switch (ahci->fingerprint) {
195     case AHCI_INTEL_ICH9:
196         /* ICH9 has a register at PCI 0x92 that
197          * acts as a master port enabler mask. */
198         reg = qpci_config_readb(ahci->dev, 0x92);
199         reg |= 0x3F;
200         qpci_config_writeb(ahci->dev, 0x92, reg);
201         /* 0...0111111b -- bit significant, ports 0-5 enabled. */
202         ASSERT_BIT_SET(qpci_config_readb(ahci->dev, 0x92), 0x3F);
203         break;
204     }
205
206 }
207
208 /**
209  * Map BAR5/ABAR, and engage the PCI device.
210  */
211 void start_ahci_device(AHCIQState *ahci)
212 {
213     /* Map AHCI's ABAR (BAR5) */
214     ahci->hba_base = qpci_iomap(ahci->dev, 5, &ahci->barsize);
215     g_assert(ahci->hba_base);
216
217     /* turns on pci.cmd.iose, pci.cmd.mse and pci.cmd.bme */
218     qpci_device_enable(ahci->dev);
219 }
220
221 /**
222  * Test and initialize the AHCI's HBA memory areas.
223  * Initialize and start any ports with devices attached.
224  * Bring the HBA into the idle state.
225  */
226 void ahci_hba_enable(AHCIQState *ahci)
227 {
228     /* Bits of interest in this section:
229      * GHC.AE     Global Host Control / AHCI Enable
230      * PxCMD.ST   Port Command: Start
231      * PxCMD.SUD  "Spin Up Device"
232      * PxCMD.POD  "Power On Device"
233      * PxCMD.FRE  "FIS Receive Enable"
234      * PxCMD.FR   "FIS Receive Running"
235      * PxCMD.CR   "Command List Running"
236      */
237     uint32_t reg, ports_impl;
238     uint16_t i;
239     uint8_t num_cmd_slots;
240
241     g_assert(ahci != NULL);
242
243     /* Set GHC.AE to 1 */
244     ahci_set(ahci, AHCI_GHC, AHCI_GHC_AE);
245     reg = ahci_rreg(ahci, AHCI_GHC);
246     ASSERT_BIT_SET(reg, AHCI_GHC_AE);
247
248     /* Cache CAP and CAP2. */
249     ahci->cap = ahci_rreg(ahci, AHCI_CAP);
250     ahci->cap2 = ahci_rreg(ahci, AHCI_CAP2);
251
252     /* Read CAP.NCS, how many command slots do we have? */
253     num_cmd_slots = ((ahci->cap & AHCI_CAP_NCS) >> ctzl(AHCI_CAP_NCS)) + 1;
254     g_test_message("Number of Command Slots: %u", num_cmd_slots);
255
256     /* Determine which ports are implemented. */
257     ports_impl = ahci_rreg(ahci, AHCI_PI);
258
259     for (i = 0; ports_impl; ports_impl >>= 1, ++i) {
260         if (!(ports_impl & 0x01)) {
261             continue;
262         }
263
264         g_test_message("Initializing port %u", i);
265
266         reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);
267         if (BITCLR(reg, AHCI_PX_CMD_ST | AHCI_PX_CMD_CR |
268                    AHCI_PX_CMD_FRE | AHCI_PX_CMD_FR)) {
269             g_test_message("port is idle");
270         } else {
271             g_test_message("port needs to be idled");
272             ahci_px_clr(ahci, i, AHCI_PX_CMD,
273                         (AHCI_PX_CMD_ST | AHCI_PX_CMD_FRE));
274             /* The port has 500ms to disengage. */
275             usleep(500000);
276             reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);
277             ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_CR);
278             ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_FR);
279             g_test_message("port is now idle");
280             /* The spec does allow for possibly needing a PORT RESET
281              * or HBA reset if we fail to idle the port. */
282         }
283
284         /* Allocate Memory for the Command List Buffer & FIS Buffer */
285         /* PxCLB space ... 0x20 per command, as in 4.2.2 p 36 */
286         ahci->port[i].clb = ahci_alloc(ahci, num_cmd_slots * 0x20);
287         qmemset(ahci->port[i].clb, 0x00, num_cmd_slots * 0x20);
288         g_test_message("CLB: 0x%08" PRIx64, ahci->port[i].clb);
289         ahci_px_wreg(ahci, i, AHCI_PX_CLB, ahci->port[i].clb);
290         g_assert_cmphex(ahci->port[i].clb, ==,
291                         ahci_px_rreg(ahci, i, AHCI_PX_CLB));
292
293         /* PxFB space ... 0x100, as in 4.2.1 p 35 */
294         ahci->port[i].fb = ahci_alloc(ahci, 0x100);
295         qmemset(ahci->port[i].fb, 0x00, 0x100);
296         g_test_message("FB: 0x%08" PRIx64, ahci->port[i].fb);
297         ahci_px_wreg(ahci, i, AHCI_PX_FB, ahci->port[i].fb);
298         g_assert_cmphex(ahci->port[i].fb, ==,
299                         ahci_px_rreg(ahci, i, AHCI_PX_FB));
300
301         /* Clear PxSERR, PxIS, then IS.IPS[x] by writing '1's. */
302         ahci_px_wreg(ahci, i, AHCI_PX_SERR, 0xFFFFFFFF);
303         ahci_px_wreg(ahci, i, AHCI_PX_IS, 0xFFFFFFFF);
304         ahci_wreg(ahci, AHCI_IS, (1 << i));
305
306         /* Verify Interrupts Cleared */
307         reg = ahci_px_rreg(ahci, i, AHCI_PX_SERR);
308         g_assert_cmphex(reg, ==, 0);
309
310         reg = ahci_px_rreg(ahci, i, AHCI_PX_IS);
311         g_assert_cmphex(reg, ==, 0);
312
313         reg = ahci_rreg(ahci, AHCI_IS);
314         ASSERT_BIT_CLEAR(reg, (1 << i));
315
316         /* Enable All Interrupts: */
317         ahci_px_wreg(ahci, i, AHCI_PX_IE, 0xFFFFFFFF);
318         reg = ahci_px_rreg(ahci, i, AHCI_PX_IE);
319         g_assert_cmphex(reg, ==, ~((uint32_t)AHCI_PX_IE_RESERVED));
320
321         /* Enable the FIS Receive Engine. */
322         ahci_px_set(ahci, i, AHCI_PX_CMD, AHCI_PX_CMD_FRE);
323         reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);
324         ASSERT_BIT_SET(reg, AHCI_PX_CMD_FR);
325
326         /* AHCI 1.3 spec: if !STS.BSY, !STS.DRQ and PxSSTS.DET indicates
327          * physical presence, a device is present and may be started. However,
328          * PxSERR.DIAG.X /may/ need to be cleared a priori. */
329         reg = ahci_px_rreg(ahci, i, AHCI_PX_SERR);
330         if (BITSET(reg, AHCI_PX_SERR_DIAG_X)) {
331             ahci_px_set(ahci, i, AHCI_PX_SERR, AHCI_PX_SERR_DIAG_X);
332         }
333
334         reg = ahci_px_rreg(ahci, i, AHCI_PX_TFD);
335         if (BITCLR(reg, AHCI_PX_TFD_STS_BSY | AHCI_PX_TFD_STS_DRQ)) {
336             reg = ahci_px_rreg(ahci, i, AHCI_PX_SSTS);
337             if ((reg & AHCI_PX_SSTS_DET) == SSTS_DET_ESTABLISHED) {
338                 /* Device Found: set PxCMD.ST := 1 */
339                 ahci_px_set(ahci, i, AHCI_PX_CMD, AHCI_PX_CMD_ST);
340                 ASSERT_BIT_SET(ahci_px_rreg(ahci, i, AHCI_PX_CMD),
341                                AHCI_PX_CMD_CR);
342                 g_test_message("Started Device %u", i);
343             } else if ((reg & AHCI_PX_SSTS_DET)) {
344                 /* Device present, but in some unknown state. */
345                 g_assert_not_reached();
346             }
347         }
348     }
349
350     /* Enable GHC.IE */
351     ahci_set(ahci, AHCI_GHC, AHCI_GHC_IE);
352     reg = ahci_rreg(ahci, AHCI_GHC);
353     ASSERT_BIT_SET(reg, AHCI_GHC_IE);
354
355     /* TODO: The device should now be idling and waiting for commands.
356      * In the future, a small test-case to inspect the Register D2H FIS
357      * and clear the initial interrupts might be good. */
358 }
359
360 /**
361  * Pick the first implemented and running port
362  */
363 unsigned ahci_port_select(AHCIQState *ahci)
364 {
365     uint32_t ports, reg;
366     unsigned i;
367
368     ports = ahci_rreg(ahci, AHCI_PI);
369     for (i = 0; i < 32; ports >>= 1, ++i) {
370         if (ports == 0) {
371             i = 32;
372         }
373
374         if (!(ports & 0x01)) {
375             continue;
376         }
377
378         reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);
379         if (BITSET(reg, AHCI_PX_CMD_ST)) {
380             break;
381         }
382     }
383     g_assert(i < 32);
384     return i;
385 }
386
387 /**
388  * Clear a port's interrupts and status information prior to a test.
389  */
390 void ahci_port_clear(AHCIQState *ahci, uint8_t port)
391 {
392     uint32_t reg;
393
394     /* Clear out this port's interrupts (ignore the init register d2h fis) */
395     reg = ahci_px_rreg(ahci, port, AHCI_PX_IS);
396     ahci_px_wreg(ahci, port, AHCI_PX_IS, reg);
397     g_assert_cmphex(ahci_px_rreg(ahci, port, AHCI_PX_IS), ==, 0);
398
399     /* Wipe the FIS-Receive Buffer */
400     qmemset(ahci->port[port].fb, 0x00, 0x100);
401 }
402
403 /**
404  * Check a port for errors.
405  */
406 void ahci_port_check_error(AHCIQState *ahci, uint8_t port)
407 {
408     uint32_t reg;
409
410     /* The upper 9 bits of the IS register all indicate errors. */
411     reg = ahci_px_rreg(ahci, port, AHCI_PX_IS);
412     reg >>= 23;
413     g_assert_cmphex(reg, ==, 0);
414
415     /* The Sata Error Register should be empty. */
416     reg = ahci_px_rreg(ahci, port, AHCI_PX_SERR);
417     g_assert_cmphex(reg, ==, 0);
418
419     /* The TFD also has two error sections. */
420     reg = ahci_px_rreg(ahci, port, AHCI_PX_TFD);
421     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_STS_ERR);
422     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_ERR);
423 }
424
425 void ahci_port_check_interrupts(AHCIQState *ahci, uint8_t port,
426                                 uint32_t intr_mask)
427 {
428     uint32_t reg;
429
430     /* Check for expected interrupts */
431     reg = ahci_px_rreg(ahci, port, AHCI_PX_IS);
432     ASSERT_BIT_SET(reg, intr_mask);
433
434     /* Clear expected interrupts and assert all interrupts now cleared. */
435     ahci_px_wreg(ahci, port, AHCI_PX_IS, intr_mask);
436     g_assert_cmphex(ahci_px_rreg(ahci, port, AHCI_PX_IS), ==, 0);
437 }
438
439 void ahci_port_check_nonbusy(AHCIQState *ahci, uint8_t port, uint8_t slot)
440 {
441     uint32_t reg;
442
443     /* Assert that the command slot is no longer busy (NCQ) */
444     reg = ahci_px_rreg(ahci, port, AHCI_PX_SACT);
445     ASSERT_BIT_CLEAR(reg, (1 << slot));
446
447     /* Non-NCQ */
448     reg = ahci_px_rreg(ahci, port, AHCI_PX_CI);
449     ASSERT_BIT_CLEAR(reg, (1 << slot));
450
451     /* And assert that we are generally not busy. */
452     reg = ahci_px_rreg(ahci, port, AHCI_PX_TFD);
453     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_STS_BSY);
454     ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_STS_DRQ);
455 }
456
457 void ahci_port_check_d2h_sanity(AHCIQState *ahci, uint8_t port, uint8_t slot)
458 {
459     RegD2HFIS *d2h = g_malloc0(0x20);
460     uint32_t reg;
461
462     memread(ahci->port[port].fb + 0x40, d2h, 0x20);
463     g_assert_cmphex(d2h->fis_type, ==, 0x34);
464
465     reg = ahci_px_rreg(ahci, port, AHCI_PX_TFD);
466     g_assert_cmphex((reg & AHCI_PX_TFD_ERR) >> 8, ==, d2h->error);
467     g_assert_cmphex((reg & AHCI_PX_TFD_STS), ==, d2h->status);
468
469     g_free(d2h);
470 }
471
472 void ahci_port_check_pio_sanity(AHCIQState *ahci, uint8_t port,
473                                 uint8_t slot, size_t buffsize)
474 {
475     PIOSetupFIS *pio = g_malloc0(0x20);
476
477     /* We cannot check the Status or E_Status registers, because
478      * the status may have again changed between the PIO Setup FIS
479      * and the conclusion of the command with the D2H Register FIS. */
480     memread(ahci->port[port].fb + 0x20, pio, 0x20);
481     g_assert_cmphex(pio->fis_type, ==, 0x5f);
482
483     /* BUG: PIO Setup FIS as utilized by QEMU tries to fit the entire
484      * transfer size in a uint16_t field. The maximum transfer size can
485      * eclipse this; the field is meant to convey the size of data per
486      * each Data FIS, not the entire operation as a whole. For now,
487      * we will sanity check the broken case where applicable. */
488     if (buffsize <= UINT16_MAX) {
489         g_assert_cmphex(le16_to_cpu(pio->tx_count), ==, buffsize);
490     }
491
492     g_free(pio);
493 }
494
495 void ahci_port_check_cmd_sanity(AHCIQState *ahci, AHCICommand *cmd)
496 {
497     AHCICommandHeader cmdh;
498
499     ahci_get_command_header(ahci, cmd->port, cmd->slot, &cmdh);
500     /* Physical Region Descriptor Byte Count is not required to work for NCQ. */
501     if (!cmd->props->ncq) {
502         g_assert_cmphex(cmd->xbytes, ==, cmdh.prdbc);
503     }
504 }
505
506 /* Get the command in #slot of port #port. */
507 void ahci_get_command_header(AHCIQState *ahci, uint8_t port,
508                              uint8_t slot, AHCICommandHeader *cmd)
509 {
510     uint64_t ba = ahci->port[port].clb;
511     ba += slot * sizeof(AHCICommandHeader);
512     memread(ba, cmd, sizeof(AHCICommandHeader));
513
514     cmd->flags = le16_to_cpu(cmd->flags);
515     cmd->prdtl = le16_to_cpu(cmd->prdtl);
516     cmd->prdbc = le32_to_cpu(cmd->prdbc);
517     cmd->ctba = le64_to_cpu(cmd->ctba);
518 }
519
520 /* Set the command in #slot of port #port. */
521 void ahci_set_command_header(AHCIQState *ahci, uint8_t port,
522                              uint8_t slot, AHCICommandHeader *cmd)
523 {
524     AHCICommandHeader tmp = { .flags = 0 };
525     uint64_t ba = ahci->port[port].clb;
526     ba += slot * sizeof(AHCICommandHeader);
527
528     tmp.flags = cpu_to_le16(cmd->flags);
529     tmp.prdtl = cpu_to_le16(cmd->prdtl);
530     tmp.prdbc = cpu_to_le32(cmd->prdbc);
531     tmp.ctba = cpu_to_le64(cmd->ctba);
532
533     memwrite(ba, &tmp, sizeof(AHCICommandHeader));
534 }
535
536 void ahci_destroy_command(AHCIQState *ahci, uint8_t port, uint8_t slot)
537 {
538     AHCICommandHeader cmd;
539
540     /* Obtain the Nth Command Header */
541     ahci_get_command_header(ahci, port, slot, &cmd);
542     if (cmd.ctba == 0) {
543         /* No address in it, so just return -- it's empty. */
544         goto tidy;
545     }
546
547     /* Free the Table */
548     ahci_free(ahci, cmd.ctba);
549
550  tidy:
551     /* NULL the header. */
552     memset(&cmd, 0x00, sizeof(cmd));
553     ahci_set_command_header(ahci, port, slot, &cmd);
554     ahci->port[port].ctba[slot] = 0;
555     ahci->port[port].prdtl[slot] = 0;
556 }
557
558 void ahci_write_fis(AHCIQState *ahci, AHCICommand *cmd)
559 {
560     RegH2DFIS tmp = cmd->fis;
561     uint64_t addr = cmd->header.ctba;
562
563     /* NCQ commands use exclusively 8 bit fields and needs no adjustment.
564      * Only the count field needs to be adjusted for non-NCQ commands.
565      * The auxiliary FIS fields are defined per-command and are not currently
566      * implemented in libqos/ahci.o, but may or may not need to be flipped. */
567     if (!cmd->props->ncq) {
568         tmp.count = cpu_to_le16(tmp.count);
569     }
570
571     memwrite(addr, &tmp, sizeof(tmp));
572 }
573
574 unsigned ahci_pick_cmd(AHCIQState *ahci, uint8_t port)
575 {
576     unsigned i;
577     unsigned j;
578     uint32_t reg;
579
580     reg = ahci_px_rreg(ahci, port, AHCI_PX_CI);
581
582     /* Pick the least recently used command slot that's available */
583     for (i = 0; i < 32; ++i) {
584         j = ((ahci->port[port].next + i) % 32);
585         if (reg & (1 << j)) {
586             continue;
587         }
588         ahci_destroy_command(ahci, port, j);
589         ahci->port[port].next = (j + 1) % 32;
590         return j;
591     }
592
593     g_test_message("All command slots were busy.");
594     g_assert_not_reached();
595 }
596
597 inline unsigned size_to_prdtl(unsigned bytes, unsigned bytes_per_prd)
598 {
599     /* Each PRD can describe up to 4MiB */
600     g_assert_cmphex(bytes_per_prd, <=, 4096 * 1024);
601     g_assert_cmphex(bytes_per_prd & 0x01, ==, 0x00);
602     return (bytes + bytes_per_prd - 1) / bytes_per_prd;
603 }
604
605 const AHCIOpts default_opts = { .size = 0 };
606
607 /**
608  * ahci_exec: execute a given command on a specific
609  * AHCI port.
610  *
611  * @ahci: The device to send the command to
612  * @port: The port number of the SATA device we wish
613  *        to have execute this command
614  * @op:   The S/ATA command to execute, or if opts.atapi
615  *        is true, the SCSI command code.
616  * @opts: Optional arguments to modify execution behavior.
617  */
618 void ahci_exec(AHCIQState *ahci, uint8_t port,
619                uint8_t op, const AHCIOpts *opts_in)
620 {
621     AHCICommand *cmd;
622     int rc;
623     AHCIOpts *opts;
624
625     opts = g_memdup((opts_in == NULL ? &default_opts : opts_in),
626                     sizeof(AHCIOpts));
627
628     /* No guest buffer provided, create one. */
629     if (opts->size && !opts->buffer) {
630         opts->buffer = ahci_alloc(ahci, opts->size);
631         g_assert(opts->buffer);
632         qmemset(opts->buffer, 0x00, opts->size);
633     }
634
635     /* Command creation */
636     if (opts->atapi) {
637         cmd = ahci_atapi_command_create(op);
638         if (opts->atapi_dma) {
639             ahci_command_enable_atapi_dma(cmd);
640         }
641     } else {
642         cmd = ahci_command_create(op);
643     }
644     ahci_command_adjust(cmd, opts->lba, opts->buffer,
645                         opts->size, opts->prd_size);
646
647     if (opts->pre_cb) {
648         rc = opts->pre_cb(ahci, cmd, opts);
649         g_assert_cmpint(rc, ==, 0);
650     }
651
652     /* Write command to memory and issue it */
653     ahci_command_commit(ahci, cmd, port);
654     ahci_command_issue_async(ahci, cmd);
655     if (opts->error) {
656         qmp_eventwait("STOP");
657     }
658     if (opts->mid_cb) {
659         rc = opts->mid_cb(ahci, cmd, opts);
660         g_assert_cmpint(rc, ==, 0);
661     }
662     if (opts->error) {
663         qmp_async("{'execute':'cont' }");
664         qmp_eventwait("RESUME");
665     }
666
667     /* Wait for command to complete and verify sanity */
668     ahci_command_wait(ahci, cmd);
669     ahci_command_verify(ahci, cmd);
670     if (opts->post_cb) {
671         rc = opts->post_cb(ahci, cmd, opts);
672         g_assert_cmpint(rc, ==, 0);
673     }
674     ahci_command_free(cmd);
675     if (opts->buffer != opts_in->buffer) {
676         ahci_free(ahci, opts->buffer);
677     }
678     g_free(opts);
679 }
680
681 /* Issue a command, expecting it to fail and STOP the VM */
682 AHCICommand *ahci_guest_io_halt(AHCIQState *ahci, uint8_t port,
683                                 uint8_t ide_cmd, uint64_t buffer,
684                                 size_t bufsize, uint64_t sector)
685 {
686     AHCICommand *cmd;
687
688     cmd = ahci_command_create(ide_cmd);
689     ahci_command_adjust(cmd, sector, buffer, bufsize, 0);
690     ahci_command_commit(ahci, cmd, port);
691     ahci_command_issue_async(ahci, cmd);
692     qmp_eventwait("STOP");
693
694     return cmd;
695 }
696
697 /* Resume a previously failed command and verify/finalize */
698 void ahci_guest_io_resume(AHCIQState *ahci, AHCICommand *cmd)
699 {
700     /* Complete the command */
701     qmp_async("{'execute':'cont' }");
702     qmp_eventwait("RESUME");
703     ahci_command_wait(ahci, cmd);
704     ahci_command_verify(ahci, cmd);
705     ahci_command_free(cmd);
706 }
707
708 /* Given a guest buffer address, perform an IO operation */
709 void ahci_guest_io(AHCIQState *ahci, uint8_t port, uint8_t ide_cmd,
710                    uint64_t buffer, size_t bufsize, uint64_t sector)
711 {
712     AHCICommand *cmd;
713     cmd = ahci_command_create(ide_cmd);
714     ahci_command_set_buffer(cmd, buffer);
715     ahci_command_set_size(cmd, bufsize);
716     if (sector) {
717         ahci_command_set_offset(cmd, sector);
718     }
719     ahci_command_commit(ahci, cmd, port);
720     ahci_command_issue(ahci, cmd);
721     ahci_command_verify(ahci, cmd);
722     ahci_command_free(cmd);
723 }
724
725 static AHCICommandProp *ahci_command_find(uint8_t command_name)
726 {
727     int i;
728
729     for (i = 0; i < ARRAY_SIZE(ahci_command_properties); i++) {
730         if (ahci_command_properties[i].cmd == command_name) {
731             return &ahci_command_properties[i];
732         }
733     }
734
735     return NULL;
736 }
737
738 /* Given a HOST buffer, create a buffer address and perform an IO operation. */
739 void ahci_io(AHCIQState *ahci, uint8_t port, uint8_t ide_cmd,
740              void *buffer, size_t bufsize, uint64_t sector)
741 {
742     uint64_t ptr;
743     AHCICommandProp *props;
744
745     props = ahci_command_find(ide_cmd);
746     g_assert(props);
747     ptr = ahci_alloc(ahci, bufsize);
748     g_assert(!bufsize || ptr);
749     qmemset(ptr, 0x00, bufsize);
750
751     if (bufsize && props->write) {
752         bufwrite(ptr, buffer, bufsize);
753     }
754
755     ahci_guest_io(ahci, port, ide_cmd, ptr, bufsize, sector);
756
757     if (bufsize && props->read) {
758         bufread(ptr, buffer, bufsize);
759     }
760
761     ahci_free(ahci, ptr);
762 }
763
764 /**
765  * Initializes a basic command header in memory.
766  * We assume that this is for an ATA command using RegH2DFIS.
767  */
768 static void command_header_init(AHCICommand *cmd)
769 {
770     AHCICommandHeader *hdr = &cmd->header;
771     AHCICommandProp *props = cmd->props;
772
773     hdr->flags = 5;             /* RegH2DFIS is 5 DW long. Must be < 32 */
774     hdr->flags |= CMDH_CLR_BSY; /* Clear the BSY bit when done */
775     if (props->write) {
776         hdr->flags |= CMDH_WRITE;
777     }
778     if (props->atapi) {
779         hdr->flags |= CMDH_ATAPI;
780     }
781     /* Other flags: PREFETCH, RESET, and BIST */
782     hdr->prdtl = size_to_prdtl(cmd->xbytes, cmd->prd_size);
783     hdr->prdbc = 0;
784     hdr->ctba = 0;
785 }
786
787 static void command_table_init(AHCICommand *cmd)
788 {
789     RegH2DFIS *fis = &(cmd->fis);
790     uint16_t sect_count = (cmd->xbytes / AHCI_SECTOR_SIZE);
791
792     fis->fis_type = REG_H2D_FIS;
793     fis->flags = REG_H2D_FIS_CMD; /* "Command" bit */
794     fis->command = cmd->name;
795
796     if (cmd->props->ncq) {
797         NCQFIS *ncqfis = (NCQFIS *)fis;
798         /* NCQ is weird and re-uses FIS frames for unrelated data.
799          * See SATA 3.2, 13.6.4.1 READ FPDMA QUEUED for an example. */
800         ncqfis->sector_low = sect_count & 0xFF;
801         ncqfis->sector_hi = (sect_count >> 8) & 0xFF;
802         ncqfis->device = NCQ_DEVICE_MAGIC;
803         /* Force Unit Access is bit 7 in the device register */
804         ncqfis->tag = 0;  /* bits 3-7 are the NCQ tag */
805         ncqfis->prio = 0; /* bits 6,7 are a prio tag */
806         /* RARC bit is bit 0 of TAG field */
807     } else {
808         fis->feature_low = 0x00;
809         fis->feature_high = 0x00;
810         if (cmd->props->lba28 || cmd->props->lba48) {
811             fis->device = ATA_DEVICE_LBA;
812         }
813         fis->count = (cmd->xbytes / AHCI_SECTOR_SIZE);
814     }
815     fis->icc = 0x00;
816     fis->control = 0x00;
817     memset(fis->aux, 0x00, ARRAY_SIZE(fis->aux));
818 }
819
820 void ahci_command_enable_atapi_dma(AHCICommand *cmd)
821 {
822     RegH2DFIS *fis = &(cmd->fis);
823     g_assert(cmd->props->atapi);
824     fis->feature_low |= 0x01;
825     cmd->interrupts &= ~AHCI_PX_IS_PSS;
826     cmd->props->dma = true;
827     cmd->props->pio = false;
828     /* BUG: We expect the DMA Setup interrupt for DMA commands */
829     /* cmd->interrupts |= AHCI_PX_IS_DSS; */
830 }
831
832 AHCICommand *ahci_command_create(uint8_t command_name)
833 {
834     AHCICommandProp *props = ahci_command_find(command_name);
835     AHCICommand *cmd;
836
837     g_assert(props);
838     cmd = g_malloc0(sizeof(AHCICommand));
839     g_assert(!(props->dma && props->pio));
840     g_assert(!(props->lba28 && props->lba48));
841     g_assert(!(props->read && props->write));
842     g_assert(!props->size || props->data);
843     g_assert(!props->ncq || props->lba48);
844
845     /* Defaults and book-keeping */
846     cmd->props = g_memdup(props, sizeof(AHCICommandProp));
847     cmd->name = command_name;
848     cmd->xbytes = props->size;
849     cmd->prd_size = 4096;
850     cmd->buffer = 0xabad1dea;
851
852     if (!cmd->props->ncq) {
853         cmd->interrupts = AHCI_PX_IS_DHRS;
854     }
855     /* BUG: We expect the DPS interrupt for data commands */
856     /* cmd->interrupts |= props->data ? AHCI_PX_IS_DPS : 0; */
857     /* BUG: We expect the DMA Setup interrupt for DMA commands */
858     /* cmd->interrupts |= props->dma ? AHCI_PX_IS_DSS : 0; */
859     cmd->interrupts |= props->pio ? AHCI_PX_IS_PSS : 0;
860     cmd->interrupts |= props->ncq ? AHCI_PX_IS_SDBS : 0;
861
862     command_header_init(cmd);
863     command_table_init(cmd);
864
865     return cmd;
866 }
867
868 AHCICommand *ahci_atapi_command_create(uint8_t scsi_cmd)
869 {
870     AHCICommand *cmd = ahci_command_create(CMD_PACKET);
871     cmd->atapi_cmd = g_malloc0(16);
872     cmd->atapi_cmd[0] = scsi_cmd;
873     /* ATAPI needs a PIO transfer chunk size set inside of the LBA registers.
874      * The block/sector size is a natural default. */
875     cmd->fis.lba_lo[1] = ATAPI_SECTOR_SIZE >> 8 & 0xFF;
876     cmd->fis.lba_lo[2] = ATAPI_SECTOR_SIZE & 0xFF;
877
878     return cmd;
879 }
880
881 void ahci_command_free(AHCICommand *cmd)
882 {
883     g_free(cmd->atapi_cmd);
884     g_free(cmd->props);
885     g_free(cmd);
886 }
887
888 void ahci_command_set_flags(AHCICommand *cmd, uint16_t cmdh_flags)
889 {
890     cmd->header.flags |= cmdh_flags;
891 }
892
893 void ahci_command_clr_flags(AHCICommand *cmd, uint16_t cmdh_flags)
894 {
895     cmd->header.flags &= ~cmdh_flags;
896 }
897
898 static void ahci_atapi_command_set_offset(AHCICommand *cmd, uint64_t lba)
899 {
900     unsigned char *cbd = cmd->atapi_cmd;
901     g_assert(cbd);
902
903     switch (cbd[0]) {
904     case CMD_ATAPI_READ_10:
905         g_assert_cmpuint(lba, <=, UINT32_MAX);
906         stl_be_p(&cbd[2], lba);
907         break;
908     default:
909         /* SCSI doesn't have uniform packet formats,
910          * so you have to add support for it manually. Sorry! */
911         g_assert_not_reached();
912     }
913 }
914
915 void ahci_command_set_offset(AHCICommand *cmd, uint64_t lba_sect)
916 {
917     RegH2DFIS *fis = &(cmd->fis);
918
919     if (cmd->props->atapi) {
920         ahci_atapi_command_set_offset(cmd, lba_sect);
921         return;
922     } else if (!cmd->props->data && !lba_sect) {
923         /* Not meaningful, ignore. */
924         return;
925     } else if (cmd->props->lba28) {
926         g_assert_cmphex(lba_sect, <=, 0xFFFFFFF);
927     } else if (cmd->props->lba48 || cmd->props->ncq) {
928         g_assert_cmphex(lba_sect, <=, 0xFFFFFFFFFFFF);
929     } else {
930         /* Can't set offset if we don't know the format. */
931         g_assert_not_reached();
932     }
933
934     /* LBA28 uses the low nibble of the device/control register for LBA24:27 */
935     fis->lba_lo[0] = (lba_sect & 0xFF);
936     fis->lba_lo[1] = (lba_sect >> 8) & 0xFF;
937     fis->lba_lo[2] = (lba_sect >> 16) & 0xFF;
938     if (cmd->props->lba28) {
939         fis->device = (fis->device & 0xF0) | ((lba_sect >> 24) & 0x0F);
940     }
941     fis->lba_hi[0] = (lba_sect >> 24) & 0xFF;
942     fis->lba_hi[1] = (lba_sect >> 32) & 0xFF;
943     fis->lba_hi[2] = (lba_sect >> 40) & 0xFF;
944 }
945
946 void ahci_command_set_buffer(AHCICommand *cmd, uint64_t buffer)
947 {
948     cmd->buffer = buffer;
949 }
950
951 static void ahci_atapi_set_size(AHCICommand *cmd, uint64_t xbytes)
952 {
953     unsigned char *cbd = cmd->atapi_cmd;
954     uint64_t nsectors = xbytes / 2048;
955     g_assert(cbd);
956
957     switch (cbd[0]) {
958     case CMD_ATAPI_READ_10:
959         g_assert_cmpuint(nsectors, <=, UINT16_MAX);
960         stw_be_p(&cbd[7], nsectors);
961         break;
962     default:
963         /* SCSI doesn't have uniform packet formats,
964          * so you have to add support for it manually. Sorry! */
965         g_assert_not_reached();
966     }
967 }
968
969 void ahci_command_set_sizes(AHCICommand *cmd, uint64_t xbytes,
970                             unsigned prd_size)
971 {
972     uint16_t sect_count;
973
974     /* Each PRD can describe up to 4MiB, and must not be odd. */
975     g_assert_cmphex(prd_size, <=, 4096 * 1024);
976     g_assert_cmphex(prd_size & 0x01, ==, 0x00);
977     if (prd_size) {
978         cmd->prd_size = prd_size;
979     }
980     cmd->xbytes = xbytes;
981     sect_count = (cmd->xbytes / AHCI_SECTOR_SIZE);
982
983     if (cmd->props->ncq) {
984         NCQFIS *nfis = (NCQFIS *)&(cmd->fis);
985         nfis->sector_low = sect_count & 0xFF;
986         nfis->sector_hi = (sect_count >> 8) & 0xFF;
987     } else if (cmd->props->atapi) {
988         ahci_atapi_set_size(cmd, xbytes);
989     } else {
990         cmd->fis.count = sect_count;
991     }
992     cmd->header.prdtl = size_to_prdtl(cmd->xbytes, cmd->prd_size);
993 }
994
995 void ahci_command_set_size(AHCICommand *cmd, uint64_t xbytes)
996 {
997     ahci_command_set_sizes(cmd, xbytes, cmd->prd_size);
998 }
999
1000 void ahci_command_set_prd_size(AHCICommand *cmd, unsigned prd_size)
1001 {
1002     ahci_command_set_sizes(cmd, cmd->xbytes, prd_size);
1003 }
1004
1005 void ahci_command_adjust(AHCICommand *cmd, uint64_t offset, uint64_t buffer,
1006                          uint64_t xbytes, unsigned prd_size)
1007 {
1008     ahci_command_set_sizes(cmd, xbytes, prd_size);
1009     ahci_command_set_buffer(cmd, buffer);
1010     ahci_command_set_offset(cmd, offset);
1011 }
1012
1013 void ahci_command_commit(AHCIQState *ahci, AHCICommand *cmd, uint8_t port)
1014 {
1015     uint16_t i, prdtl;
1016     uint64_t table_size, table_ptr, remaining;
1017     PRD prd;
1018
1019     /* This command is now tied to this port/command slot */
1020     cmd->port = port;
1021     cmd->slot = ahci_pick_cmd(ahci, port);
1022
1023     if (cmd->props->ncq) {
1024         NCQFIS *nfis = (NCQFIS *)&cmd->fis;
1025         nfis->tag = (cmd->slot << 3) & 0xFC;
1026     }
1027
1028     /* Create a buffer for the command table */
1029     prdtl = size_to_prdtl(cmd->xbytes, cmd->prd_size);
1030     table_size = CMD_TBL_SIZ(prdtl);
1031     table_ptr = ahci_alloc(ahci, table_size);
1032     g_assert(table_ptr);
1033     /* AHCI 1.3: Must be aligned to 0x80 */
1034     g_assert((table_ptr & 0x7F) == 0x00);
1035     cmd->header.ctba = table_ptr;
1036
1037     /* Commit the command header (part of the Command List Buffer) */
1038     ahci_set_command_header(ahci, port, cmd->slot, &(cmd->header));
1039     /* Now, write the command table (FIS, ACMD, and PRDT) -- FIS first, */
1040     ahci_write_fis(ahci, cmd);
1041     /* Then ATAPI CMD, if needed */
1042     if (cmd->props->atapi) {
1043         memwrite(table_ptr + 0x40, cmd->atapi_cmd, 16);
1044     }
1045
1046     /* Construct and write the PRDs to the command table */
1047     g_assert_cmphex(prdtl, ==, cmd->header.prdtl);
1048     remaining = cmd->xbytes;
1049     for (i = 0; i < prdtl; ++i) {
1050         prd.dba = cpu_to_le64(cmd->buffer + (cmd->prd_size * i));
1051         prd.res = 0;
1052         if (remaining > cmd->prd_size) {
1053             /* Note that byte count is 0-based. */
1054             prd.dbc = cpu_to_le32(cmd->prd_size - 1);
1055             remaining -= cmd->prd_size;
1056         } else {
1057             /* Again, dbc is 0-based. */
1058             prd.dbc = cpu_to_le32(remaining - 1);
1059             remaining = 0;
1060         }
1061         prd.dbc |= cpu_to_le32(0x80000000); /* Request DPS Interrupt */
1062
1063         /* Commit the PRD entry to the Command Table */
1064         memwrite(table_ptr + 0x80 + (i * sizeof(PRD)),
1065                  &prd, sizeof(PRD));
1066     }
1067
1068     /* Bookmark the PRDTL and CTBA values */
1069     ahci->port[port].ctba[cmd->slot] = table_ptr;
1070     ahci->port[port].prdtl[cmd->slot] = prdtl;
1071 }
1072
1073 void ahci_command_issue_async(AHCIQState *ahci, AHCICommand *cmd)
1074 {
1075     if (cmd->props->ncq) {
1076         ahci_px_wreg(ahci, cmd->port, AHCI_PX_SACT, (1 << cmd->slot));
1077     }
1078
1079     ahci_px_wreg(ahci, cmd->port, AHCI_PX_CI, (1 << cmd->slot));
1080 }
1081
1082 void ahci_command_wait(AHCIQState *ahci, AHCICommand *cmd)
1083 {
1084     /* We can't rely on STS_BSY until the command has started processing.
1085      * Therefore, we also use the Command Issue bit as indication of
1086      * a command in-flight. */
1087
1088 #define RSET(REG, MASK) (BITSET(ahci_px_rreg(ahci, cmd->port, (REG)), (MASK)))
1089
1090     while (RSET(AHCI_PX_TFD, AHCI_PX_TFD_STS_BSY) ||
1091            RSET(AHCI_PX_CI, 1 << cmd->slot) ||
1092            (cmd->props->ncq && RSET(AHCI_PX_SACT, 1 << cmd->slot))) {
1093         usleep(50);
1094     }
1095
1096 }
1097
1098 void ahci_command_issue(AHCIQState *ahci, AHCICommand *cmd)
1099 {
1100     ahci_command_issue_async(ahci, cmd);
1101     ahci_command_wait(ahci, cmd);
1102 }
1103
1104 void ahci_command_verify(AHCIQState *ahci, AHCICommand *cmd)
1105 {
1106     uint8_t slot = cmd->slot;
1107     uint8_t port = cmd->port;
1108
1109     ahci_port_check_error(ahci, port);
1110     ahci_port_check_interrupts(ahci, port, cmd->interrupts);
1111     ahci_port_check_nonbusy(ahci, port, slot);
1112     ahci_port_check_cmd_sanity(ahci, cmd);
1113     if (cmd->interrupts & AHCI_PX_IS_DHRS) {
1114         ahci_port_check_d2h_sanity(ahci, port, slot);
1115     }
1116     if (cmd->props->pio) {
1117         ahci_port_check_pio_sanity(ahci, port, slot, cmd->xbytes);
1118     }
1119 }
1120
1121 uint8_t ahci_command_slot(AHCICommand *cmd)
1122 {
1123     return cmd->slot;
1124 }