xref: /qemu/hw/ide/ahci.c (revision 19f9c044)
1 /*
2  * QEMU AHCI Emulation
3  *
4  * Copyright (c) 2010 qiaochong@loongson.cn
5  * Copyright (c) 2010 Roland Elek <elek.roland@gmail.com>
6  * Copyright (c) 2010 Sebastian Herbszt <herbszt@gmx.de>
7  * Copyright (c) 2010 Alexander Graf <agraf@suse.de>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23 
24 #include "qemu/osdep.h"
25 #include "hw/irq.h"
26 #include "hw/pci/msi.h"
27 #include "hw/pci/pci.h"
28 #include "hw/qdev-properties.h"
29 #include "migration/vmstate.h"
30 
31 #include "qemu/error-report.h"
32 #include "qemu/log.h"
33 #include "qemu/main-loop.h"
34 #include "qemu/module.h"
35 #include "sysemu/block-backend.h"
36 #include "sysemu/dma.h"
37 #include "hw/ide/pci.h"
38 #include "hw/ide/ahci-pci.h"
39 #include "hw/ide/ahci-sysbus.h"
40 #include "ahci_internal.h"
41 #include "ide-internal.h"
42 
43 #include "trace.h"
44 
45 static void check_cmd(AHCIState *s, int port);
46 static void handle_cmd(AHCIState *s, int port, uint8_t slot);
47 static void ahci_reset_port(AHCIState *s, int port);
48 static bool ahci_write_fis_d2h(AHCIDevice *ad, bool d2h_fis_i);
49 static void ahci_clear_cmd_issue(AHCIDevice *ad, uint8_t slot);
50 static void ahci_init_d2h(AHCIDevice *ad);
51 static int ahci_dma_prepare_buf(const IDEDMA *dma, int32_t limit);
52 static bool ahci_map_clb_address(AHCIDevice *ad);
53 static bool ahci_map_fis_address(AHCIDevice *ad);
54 static void ahci_unmap_clb_address(AHCIDevice *ad);
55 static void ahci_unmap_fis_address(AHCIDevice *ad);
56 
57 static const char *AHCIHostReg_lookup[AHCI_HOST_REG__COUNT] = {
58     [AHCI_HOST_REG_CAP]        = "CAP",
59     [AHCI_HOST_REG_CTL]        = "GHC",
60     [AHCI_HOST_REG_IRQ_STAT]   = "IS",
61     [AHCI_HOST_REG_PORTS_IMPL] = "PI",
62     [AHCI_HOST_REG_VERSION]    = "VS",
63     [AHCI_HOST_REG_CCC_CTL]    = "CCC_CTL",
64     [AHCI_HOST_REG_CCC_PORTS]  = "CCC_PORTS",
65     [AHCI_HOST_REG_EM_LOC]     = "EM_LOC",
66     [AHCI_HOST_REG_EM_CTL]     = "EM_CTL",
67     [AHCI_HOST_REG_CAP2]       = "CAP2",
68     [AHCI_HOST_REG_BOHC]       = "BOHC",
69 };
70 
71 static const char *AHCIPortReg_lookup[AHCI_PORT_REG__COUNT] = {
72     [AHCI_PORT_REG_LST_ADDR]    = "PxCLB",
73     [AHCI_PORT_REG_LST_ADDR_HI] = "PxCLBU",
74     [AHCI_PORT_REG_FIS_ADDR]    = "PxFB",
75     [AHCI_PORT_REG_FIS_ADDR_HI] = "PxFBU",
76     [AHCI_PORT_REG_IRQ_STAT]    = "PxIS",
77     [AHCI_PORT_REG_IRQ_MASK]    = "PXIE",
78     [AHCI_PORT_REG_CMD]         = "PxCMD",
79     [7]                         = "Reserved",
80     [AHCI_PORT_REG_TFDATA]      = "PxTFD",
81     [AHCI_PORT_REG_SIG]         = "PxSIG",
82     [AHCI_PORT_REG_SCR_STAT]    = "PxSSTS",
83     [AHCI_PORT_REG_SCR_CTL]     = "PxSCTL",
84     [AHCI_PORT_REG_SCR_ERR]     = "PxSERR",
85     [AHCI_PORT_REG_SCR_ACT]     = "PxSACT",
86     [AHCI_PORT_REG_CMD_ISSUE]   = "PxCI",
87     [AHCI_PORT_REG_SCR_NOTIF]   = "PxSNTF",
88     [AHCI_PORT_REG_FIS_CTL]     = "PxFBS",
89     [AHCI_PORT_REG_DEV_SLEEP]   = "PxDEVSLP",
90     [18 ... 27]                 = "Reserved",
91     [AHCI_PORT_REG_VENDOR_1 ...
92      AHCI_PORT_REG_VENDOR_4]    = "PxVS",
93 };
94 
95 static const char *AHCIPortIRQ_lookup[AHCI_PORT_IRQ__COUNT] = {
96     [AHCI_PORT_IRQ_BIT_DHRS] = "DHRS",
97     [AHCI_PORT_IRQ_BIT_PSS]  = "PSS",
98     [AHCI_PORT_IRQ_BIT_DSS]  = "DSS",
99     [AHCI_PORT_IRQ_BIT_SDBS] = "SDBS",
100     [AHCI_PORT_IRQ_BIT_UFS]  = "UFS",
101     [AHCI_PORT_IRQ_BIT_DPS]  = "DPS",
102     [AHCI_PORT_IRQ_BIT_PCS]  = "PCS",
103     [AHCI_PORT_IRQ_BIT_DMPS] = "DMPS",
104     [8 ... 21]               = "RESERVED",
105     [AHCI_PORT_IRQ_BIT_PRCS] = "PRCS",
106     [AHCI_PORT_IRQ_BIT_IPMS] = "IPMS",
107     [AHCI_PORT_IRQ_BIT_OFS]  = "OFS",
108     [25]                     = "RESERVED",
109     [AHCI_PORT_IRQ_BIT_INFS] = "INFS",
110     [AHCI_PORT_IRQ_BIT_IFS]  = "IFS",
111     [AHCI_PORT_IRQ_BIT_HBDS] = "HBDS",
112     [AHCI_PORT_IRQ_BIT_HBFS] = "HBFS",
113     [AHCI_PORT_IRQ_BIT_TFES] = "TFES",
114     [AHCI_PORT_IRQ_BIT_CPDS] = "CPDS"
115 };
116 
117 static uint32_t ahci_port_read(AHCIState *s, int port, int offset)
118 {
119     uint32_t val;
120     AHCIPortRegs *pr = &s->dev[port].port_regs;
121     enum AHCIPortReg regnum = offset / sizeof(uint32_t);
122     assert(regnum < (AHCI_PORT_ADDR_OFFSET_LEN / sizeof(uint32_t)));
123 
124     switch (regnum) {
125     case AHCI_PORT_REG_LST_ADDR:
126         val = pr->lst_addr;
127         break;
128     case AHCI_PORT_REG_LST_ADDR_HI:
129         val = pr->lst_addr_hi;
130         break;
131     case AHCI_PORT_REG_FIS_ADDR:
132         val = pr->fis_addr;
133         break;
134     case AHCI_PORT_REG_FIS_ADDR_HI:
135         val = pr->fis_addr_hi;
136         break;
137     case AHCI_PORT_REG_IRQ_STAT:
138         val = pr->irq_stat;
139         break;
140     case AHCI_PORT_REG_IRQ_MASK:
141         val = pr->irq_mask;
142         break;
143     case AHCI_PORT_REG_CMD:
144         val = pr->cmd;
145         break;
146     case AHCI_PORT_REG_TFDATA:
147         val = pr->tfdata;
148         break;
149     case AHCI_PORT_REG_SIG:
150         val = pr->sig;
151         break;
152     case AHCI_PORT_REG_SCR_STAT:
153         if (s->dev[port].port.ifs[0].blk) {
154             val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP |
155                   SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE;
156         } else {
157             val = SATA_SCR_SSTATUS_DET_NODEV;
158         }
159         break;
160     case AHCI_PORT_REG_SCR_CTL:
161         val = pr->scr_ctl;
162         break;
163     case AHCI_PORT_REG_SCR_ERR:
164         val = pr->scr_err;
165         break;
166     case AHCI_PORT_REG_SCR_ACT:
167         val = pr->scr_act;
168         break;
169     case AHCI_PORT_REG_CMD_ISSUE:
170         val = pr->cmd_issue;
171         break;
172     default:
173         trace_ahci_port_read_default(s, port, AHCIPortReg_lookup[regnum],
174                                      offset);
175         val = 0;
176     }
177 
178     trace_ahci_port_read(s, port, AHCIPortReg_lookup[regnum], offset, val);
179     return val;
180 }
181 
182 static void ahci_irq_raise(AHCIState *s)
183 {
184     DeviceState *dev_state = s->container;
185     PCIDevice *pci_dev = (PCIDevice *) object_dynamic_cast(OBJECT(dev_state),
186                                                            TYPE_PCI_DEVICE);
187 
188     trace_ahci_irq_raise(s);
189 
190     if (pci_dev && msi_enabled(pci_dev)) {
191         msi_notify(pci_dev, 0);
192     } else {
193         qemu_irq_raise(s->irq);
194     }
195 }
196 
197 static void ahci_irq_lower(AHCIState *s)
198 {
199     DeviceState *dev_state = s->container;
200     PCIDevice *pci_dev = (PCIDevice *) object_dynamic_cast(OBJECT(dev_state),
201                                                            TYPE_PCI_DEVICE);
202 
203     trace_ahci_irq_lower(s);
204 
205     if (!pci_dev || !msi_enabled(pci_dev)) {
206         qemu_irq_lower(s->irq);
207     }
208 }
209 
210 static void ahci_check_irq(AHCIState *s)
211 {
212     int i;
213     uint32_t old_irq = s->control_regs.irqstatus;
214 
215     s->control_regs.irqstatus = 0;
216     for (i = 0; i < s->ports; i++) {
217         AHCIPortRegs *pr = &s->dev[i].port_regs;
218         if (pr->irq_stat & pr->irq_mask) {
219             s->control_regs.irqstatus |= (1 << i);
220         }
221     }
222     trace_ahci_check_irq(s, old_irq, s->control_regs.irqstatus);
223     if (s->control_regs.irqstatus &&
224         (s->control_regs.ghc & HOST_CTL_IRQ_EN)) {
225             ahci_irq_raise(s);
226     } else {
227         ahci_irq_lower(s);
228     }
229 }
230 
231 static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d,
232                              enum AHCIPortIRQ irqbit)
233 {
234     g_assert((unsigned)irqbit < 32);
235     uint32_t irq = 1U << irqbit;
236     uint32_t irqstat = d->port_regs.irq_stat | irq;
237 
238     trace_ahci_trigger_irq(s, d->port_no,
239                            AHCIPortIRQ_lookup[irqbit], irq,
240                            d->port_regs.irq_stat, irqstat,
241                            irqstat & d->port_regs.irq_mask);
242 
243     d->port_regs.irq_stat = irqstat;
244     ahci_check_irq(s);
245 }
246 
247 static void map_page(AddressSpace *as, uint8_t **ptr, uint64_t addr,
248                      uint32_t wanted)
249 {
250     hwaddr len = wanted;
251 
252     if (*ptr) {
253         dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
254     }
255 
256     *ptr = dma_memory_map(as, addr, &len, DMA_DIRECTION_FROM_DEVICE,
257                           MEMTXATTRS_UNSPECIFIED);
258     if (len < wanted && *ptr) {
259         dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
260         *ptr = NULL;
261     }
262 }
263 
264 /**
265  * Check the cmd register to see if we should start or stop
266  * the DMA or FIS RX engines.
267  *
268  * @ad: Device to dis/engage.
269  *
270  * @return 0 on success, -1 on error.
271  */
272 static int ahci_cond_start_engines(AHCIDevice *ad)
273 {
274     AHCIPortRegs *pr = &ad->port_regs;
275     bool cmd_start = pr->cmd & PORT_CMD_START;
276     bool cmd_on    = pr->cmd & PORT_CMD_LIST_ON;
277     bool fis_start = pr->cmd & PORT_CMD_FIS_RX;
278     bool fis_on    = pr->cmd & PORT_CMD_FIS_ON;
279 
280     if (cmd_start && !cmd_on) {
281         if (!ahci_map_clb_address(ad)) {
282             pr->cmd &= ~PORT_CMD_START;
283             error_report("AHCI: Failed to start DMA engine: "
284                          "bad command list buffer address");
285             return -1;
286         }
287     } else if (!cmd_start && cmd_on) {
288         ahci_unmap_clb_address(ad);
289     }
290 
291     if (fis_start && !fis_on) {
292         if (!ahci_map_fis_address(ad)) {
293             pr->cmd &= ~PORT_CMD_FIS_RX;
294             error_report("AHCI: Failed to start FIS receive engine: "
295                          "bad FIS receive buffer address");
296             return -1;
297         }
298     } else if (!fis_start && fis_on) {
299         ahci_unmap_fis_address(ad);
300     }
301 
302     return 0;
303 }
304 
305 static void ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)
306 {
307     AHCIPortRegs *pr = &s->dev[port].port_regs;
308     enum AHCIPortReg regnum = offset / sizeof(uint32_t);
309     assert(regnum < (AHCI_PORT_ADDR_OFFSET_LEN / sizeof(uint32_t)));
310     trace_ahci_port_write(s, port, AHCIPortReg_lookup[regnum], offset, val);
311 
312     switch (regnum) {
313     case AHCI_PORT_REG_LST_ADDR:
314         pr->lst_addr = val;
315         break;
316     case AHCI_PORT_REG_LST_ADDR_HI:
317         pr->lst_addr_hi = val;
318         break;
319     case AHCI_PORT_REG_FIS_ADDR:
320         pr->fis_addr = val;
321         break;
322     case AHCI_PORT_REG_FIS_ADDR_HI:
323         pr->fis_addr_hi = val;
324         break;
325     case AHCI_PORT_REG_IRQ_STAT:
326         pr->irq_stat &= ~val;
327         ahci_check_irq(s);
328         break;
329     case AHCI_PORT_REG_IRQ_MASK:
330         pr->irq_mask = val & 0xfdc000ff;
331         ahci_check_irq(s);
332         break;
333     case AHCI_PORT_REG_CMD:
334         if ((pr->cmd & PORT_CMD_START) && !(val & PORT_CMD_START)) {
335             pr->scr_act = 0;
336             pr->cmd_issue = 0;
337         }
338 
339         /* Block any Read-only fields from being set;
340          * including LIST_ON and FIS_ON.
341          * The spec requires to set ICC bits to zero after the ICC change
342          * is done. We don't support ICC state changes, therefore always
343          * force the ICC bits to zero.
344          */
345         pr->cmd = (pr->cmd & PORT_CMD_RO_MASK) |
346             (val & ~(PORT_CMD_RO_MASK | PORT_CMD_ICC_MASK));
347 
348         /* Check FIS RX and CLB engines */
349         ahci_cond_start_engines(&s->dev[port]);
350 
351         /* XXX usually the FIS would be pending on the bus here and
352            issuing deferred until the OS enables FIS receival.
353            Instead, we only submit it once - which works in most
354            cases, but is a hack. */
355         if ((pr->cmd & PORT_CMD_FIS_ON) &&
356             !s->dev[port].init_d2h_sent) {
357             ahci_init_d2h(&s->dev[port]);
358         }
359 
360         check_cmd(s, port);
361         break;
362     case AHCI_PORT_REG_TFDATA:
363     case AHCI_PORT_REG_SIG:
364     case AHCI_PORT_REG_SCR_STAT:
365         /* Read Only */
366         break;
367     case AHCI_PORT_REG_SCR_CTL:
368         if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&
369             ((val & AHCI_SCR_SCTL_DET) == 0)) {
370             ahci_reset_port(s, port);
371         }
372         pr->scr_ctl = val;
373         break;
374     case AHCI_PORT_REG_SCR_ERR:
375         pr->scr_err &= ~val;
376         break;
377     case AHCI_PORT_REG_SCR_ACT:
378         /* RW1 */
379         pr->scr_act |= val;
380         break;
381     case AHCI_PORT_REG_CMD_ISSUE:
382         pr->cmd_issue |= val;
383         check_cmd(s, port);
384         break;
385     default:
386         trace_ahci_port_write_unimpl(s, port, AHCIPortReg_lookup[regnum],
387                                      offset, val);
388         qemu_log_mask(LOG_UNIMP, "Attempted write to unimplemented register: "
389                       "AHCI port %d register %s, offset 0x%x: 0x%"PRIx32,
390                       port, AHCIPortReg_lookup[regnum], offset, val);
391         break;
392     }
393 }
394 
395 static uint64_t ahci_mem_read_32(void *opaque, hwaddr addr)
396 {
397     AHCIState *s = opaque;
398     uint32_t val = 0;
399 
400     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
401         enum AHCIHostReg regnum = addr / 4;
402         assert(regnum < AHCI_HOST_REG__COUNT);
403 
404         switch (regnum) {
405         case AHCI_HOST_REG_CAP:
406             val = s->control_regs.cap;
407             break;
408         case AHCI_HOST_REG_CTL:
409             val = s->control_regs.ghc;
410             break;
411         case AHCI_HOST_REG_IRQ_STAT:
412             val = s->control_regs.irqstatus;
413             break;
414         case AHCI_HOST_REG_PORTS_IMPL:
415             val = s->control_regs.impl;
416             break;
417         case AHCI_HOST_REG_VERSION:
418             val = s->control_regs.version;
419             break;
420         default:
421             trace_ahci_mem_read_32_host_default(s, AHCIHostReg_lookup[regnum],
422                                                 addr);
423         }
424         trace_ahci_mem_read_32_host(s, AHCIHostReg_lookup[regnum], addr, val);
425     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
426                (addr < (AHCI_PORT_REGS_START_ADDR +
427                 (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
428         val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
429                              addr & AHCI_PORT_ADDR_OFFSET_MASK);
430     } else {
431         trace_ahci_mem_read_32_default(s, addr, val);
432     }
433 
434     trace_ahci_mem_read_32(s, addr, val);
435     return val;
436 }
437 
438 
439 /**
440  * AHCI 1.3 section 3 ("HBA Memory Registers")
441  * Support unaligned 8/16/32 bit reads, and 64 bit aligned reads.
442  * Caller is responsible for masking unwanted higher order bytes.
443  */
444 static uint64_t ahci_mem_read(void *opaque, hwaddr addr, unsigned size)
445 {
446     hwaddr aligned = addr & ~0x3;
447     int ofst = addr - aligned;
448     uint64_t lo = ahci_mem_read_32(opaque, aligned);
449     uint64_t hi;
450     uint64_t val;
451 
452     /* if < 8 byte read does not cross 4 byte boundary */
453     if (ofst + size <= 4) {
454         val = lo >> (ofst * 8);
455     } else {
456         g_assert(size > 1);
457 
458         /* If the 64bit read is unaligned, we will produce undefined
459          * results. AHCI does not support unaligned 64bit reads. */
460         hi = ahci_mem_read_32(opaque, aligned + 4);
461         val = (hi << 32 | lo) >> (ofst * 8);
462     }
463 
464     trace_ahci_mem_read(opaque, size, addr, val);
465     return val;
466 }
467 
468 
469 static void ahci_mem_write(void *opaque, hwaddr addr,
470                            uint64_t val, unsigned size)
471 {
472     AHCIState *s = opaque;
473 
474     trace_ahci_mem_write(s, size, addr, val);
475 
476     /* Only aligned reads are allowed on AHCI */
477     if (addr & 3) {
478         qemu_log_mask(LOG_GUEST_ERROR,
479                       "ahci: Mis-aligned write to addr 0x%03" HWADDR_PRIX "\n",
480                       addr);
481         return;
482     }
483 
484     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
485         enum AHCIHostReg regnum = addr / 4;
486         assert(regnum < AHCI_HOST_REG__COUNT);
487 
488         switch (regnum) {
489         case AHCI_HOST_REG_CAP: /* R/WO, RO */
490             /* FIXME handle R/WO */
491             break;
492         case AHCI_HOST_REG_CTL: /* R/W */
493             if (val & HOST_CTL_RESET) {
494                 ahci_reset(s);
495             } else {
496                 s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;
497                 ahci_check_irq(s);
498             }
499             break;
500         case AHCI_HOST_REG_IRQ_STAT: /* R/WC, RO */
501             s->control_regs.irqstatus &= ~val;
502             ahci_check_irq(s);
503             break;
504         case AHCI_HOST_REG_PORTS_IMPL: /* R/WO, RO */
505             /* FIXME handle R/WO */
506             break;
507         case AHCI_HOST_REG_VERSION: /* RO */
508             /* FIXME report write? */
509             break;
510         default:
511             qemu_log_mask(LOG_UNIMP,
512                           "Attempted write to unimplemented register: "
513                           "AHCI host register %s, "
514                           "offset 0x%"PRIx64": 0x%"PRIx64,
515                           AHCIHostReg_lookup[regnum], addr, val);
516             trace_ahci_mem_write_host_unimpl(s, size,
517                                              AHCIHostReg_lookup[regnum], addr);
518         }
519         trace_ahci_mem_write_host(s, size, AHCIHostReg_lookup[regnum],
520                                      addr, val);
521     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
522                (addr < (AHCI_PORT_REGS_START_ADDR +
523                         (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
524         ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
525                         addr & AHCI_PORT_ADDR_OFFSET_MASK, val);
526     } else {
527         qemu_log_mask(LOG_UNIMP, "Attempted write to unimplemented register: "
528                       "AHCI global register at offset 0x%"PRIx64": 0x%"PRIx64,
529                       addr, val);
530         trace_ahci_mem_write_unimpl(s, size, addr, val);
531     }
532 }
533 
534 static const MemoryRegionOps ahci_mem_ops = {
535     .read = ahci_mem_read,
536     .write = ahci_mem_write,
537     .endianness = DEVICE_LITTLE_ENDIAN,
538 };
539 
540 static uint64_t ahci_idp_read(void *opaque, hwaddr addr,
541                               unsigned size)
542 {
543     AHCIState *s = opaque;
544 
545     if (addr == s->idp_offset) {
546         /* index register */
547         return s->idp_index;
548     } else if (addr == s->idp_offset + 4) {
549         /* data register - do memory read at location selected by index */
550         return ahci_mem_read(opaque, s->idp_index, size);
551     } else {
552         return 0;
553     }
554 }
555 
556 static void ahci_idp_write(void *opaque, hwaddr addr,
557                            uint64_t val, unsigned size)
558 {
559     AHCIState *s = opaque;
560 
561     if (addr == s->idp_offset) {
562         /* index register - mask off reserved bits */
563         s->idp_index = (uint32_t)val & ((AHCI_MEM_BAR_SIZE - 1) & ~3);
564     } else if (addr == s->idp_offset + 4) {
565         /* data register - do memory write at location selected by index */
566         ahci_mem_write(opaque, s->idp_index, val, size);
567     }
568 }
569 
570 static const MemoryRegionOps ahci_idp_ops = {
571     .read = ahci_idp_read,
572     .write = ahci_idp_write,
573     .endianness = DEVICE_LITTLE_ENDIAN,
574 };
575 
576 
577 static void ahci_reg_init(AHCIState *s)
578 {
579     int i;
580 
581     s->control_regs.cap = (s->ports - 1) |
582                           (AHCI_NUM_COMMAND_SLOTS << 8) |
583                           (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) |
584                           HOST_CAP_NCQ | HOST_CAP_AHCI | HOST_CAP_64;
585 
586     s->control_regs.impl = (1 << s->ports) - 1;
587 
588     s->control_regs.version = AHCI_VERSION_1_0;
589 
590     for (i = 0; i < s->ports; i++) {
591         s->dev[i].port_state = STATE_RUN;
592     }
593 }
594 
595 static void check_cmd(AHCIState *s, int port)
596 {
597     AHCIPortRegs *pr = &s->dev[port].port_regs;
598     uint8_t slot;
599 
600     if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) {
601         for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) {
602             if (pr->cmd_issue & (1U << slot)) {
603                 handle_cmd(s, port, slot);
604             }
605         }
606     }
607 }
608 
609 static void ahci_check_cmd_bh(void *opaque)
610 {
611     AHCIDevice *ad = opaque;
612 
613     qemu_bh_delete(ad->check_bh);
614     ad->check_bh = NULL;
615 
616     check_cmd(ad->hba, ad->port_no);
617 }
618 
619 static void ahci_init_d2h(AHCIDevice *ad)
620 {
621     IDEState *ide_state = &ad->port.ifs[0];
622     AHCIPortRegs *pr = &ad->port_regs;
623 
624     if (ad->init_d2h_sent) {
625         return;
626     }
627 
628     /*
629      * For simplicity, do not call ahci_clear_cmd_issue() for this
630      * ahci_write_fis_d2h(). (The reset value for PxCI is 0.)
631      */
632     if (ahci_write_fis_d2h(ad, true)) {
633         ad->init_d2h_sent = true;
634         /* We're emulating receiving the first Reg D2H FIS from the device;
635          * Update the SIG register, but otherwise proceed as normal. */
636         pr->sig = ((uint32_t)ide_state->hcyl << 24) |
637             (ide_state->lcyl << 16) |
638             (ide_state->sector << 8) |
639             (ide_state->nsector & 0xFF);
640     }
641 }
642 
643 static void ahci_set_signature(AHCIDevice *ad, uint32_t sig)
644 {
645     IDEState *s = &ad->port.ifs[0];
646     s->hcyl = sig >> 24 & 0xFF;
647     s->lcyl = sig >> 16 & 0xFF;
648     s->sector = sig >> 8 & 0xFF;
649     s->nsector = sig & 0xFF;
650 
651     trace_ahci_set_signature(ad->hba, ad->port_no, s->nsector, s->sector,
652                              s->lcyl, s->hcyl, sig);
653 }
654 
655 static void ahci_reset_port(AHCIState *s, int port)
656 {
657     AHCIDevice *d = &s->dev[port];
658     AHCIPortRegs *pr = &d->port_regs;
659     IDEState *ide_state = &d->port.ifs[0];
660     int i;
661 
662     trace_ahci_reset_port(s, port);
663 
664     ide_bus_reset(&d->port);
665     ide_state->ncq_queues = AHCI_MAX_CMDS;
666 
667     pr->scr_stat = 0;
668     pr->scr_err = 0;
669     pr->scr_act = 0;
670     pr->tfdata = 0x7F;
671     pr->sig = 0xFFFFFFFF;
672     pr->cmd_issue = 0;
673     d->busy_slot = -1;
674     d->init_d2h_sent = false;
675 
676     ide_state = &s->dev[port].port.ifs[0];
677     if (!ide_state->blk) {
678         return;
679     }
680 
681     /* reset ncq queue */
682     for (i = 0; i < AHCI_MAX_CMDS; i++) {
683         NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[i];
684         ncq_tfs->halt = false;
685         if (!ncq_tfs->used) {
686             continue;
687         }
688 
689         if (ncq_tfs->aiocb) {
690             blk_aio_cancel(ncq_tfs->aiocb);
691             ncq_tfs->aiocb = NULL;
692         }
693 
694         /* Maybe we just finished the request thanks to blk_aio_cancel() */
695         if (!ncq_tfs->used) {
696             continue;
697         }
698 
699         qemu_sglist_destroy(&ncq_tfs->sglist);
700         ncq_tfs->used = 0;
701     }
702 
703     s->dev[port].port_state = STATE_RUN;
704     if (ide_state->drive_kind == IDE_CD) {
705         ahci_set_signature(d, SATA_SIGNATURE_CDROM);
706         ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT;
707     } else {
708         ahci_set_signature(d, SATA_SIGNATURE_DISK);
709         ide_state->status = SEEK_STAT | WRERR_STAT;
710     }
711 
712     ide_state->error = 1;
713     ahci_init_d2h(d);
714 }
715 
716 /* Buffer pretty output based on a raw FIS structure. */
717 static char *ahci_pretty_buffer_fis(const uint8_t *fis, int cmd_len)
718 {
719     int i;
720     GString *s = g_string_new("FIS:");
721 
722     for (i = 0; i < cmd_len; i++) {
723         if ((i & 0xf) == 0) {
724             g_string_append_printf(s, "\n0x%02x: ", i);
725         }
726         g_string_append_printf(s, "%02x ", fis[i]);
727     }
728     g_string_append_c(s, '\n');
729 
730     return g_string_free(s, FALSE);
731 }
732 
733 static bool ahci_map_fis_address(AHCIDevice *ad)
734 {
735     AHCIPortRegs *pr = &ad->port_regs;
736     map_page(ad->hba->as, &ad->res_fis,
737              ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
738     if (ad->res_fis != NULL) {
739         pr->cmd |= PORT_CMD_FIS_ON;
740         return true;
741     }
742 
743     pr->cmd &= ~PORT_CMD_FIS_ON;
744     return false;
745 }
746 
747 static void ahci_unmap_fis_address(AHCIDevice *ad)
748 {
749     if (ad->res_fis == NULL) {
750         trace_ahci_unmap_fis_address_null(ad->hba, ad->port_no);
751         return;
752     }
753     ad->port_regs.cmd &= ~PORT_CMD_FIS_ON;
754     dma_memory_unmap(ad->hba->as, ad->res_fis, 256,
755                      DMA_DIRECTION_FROM_DEVICE, 256);
756     ad->res_fis = NULL;
757 }
758 
759 static bool ahci_map_clb_address(AHCIDevice *ad)
760 {
761     AHCIPortRegs *pr = &ad->port_regs;
762     ad->cur_cmd = NULL;
763     map_page(ad->hba->as, &ad->lst,
764              ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
765     if (ad->lst != NULL) {
766         pr->cmd |= PORT_CMD_LIST_ON;
767         return true;
768     }
769 
770     pr->cmd &= ~PORT_CMD_LIST_ON;
771     return false;
772 }
773 
774 static void ahci_unmap_clb_address(AHCIDevice *ad)
775 {
776     if (ad->lst == NULL) {
777         trace_ahci_unmap_clb_address_null(ad->hba, ad->port_no);
778         return;
779     }
780     ad->port_regs.cmd &= ~PORT_CMD_LIST_ON;
781     dma_memory_unmap(ad->hba->as, ad->lst, 1024,
782                      DMA_DIRECTION_FROM_DEVICE, 1024);
783     ad->lst = NULL;
784 }
785 
786 static void ahci_write_fis_sdb(AHCIState *s, NCQTransferState *ncq_tfs)
787 {
788     AHCIDevice *ad = ncq_tfs->drive;
789     AHCIPortRegs *pr = &ad->port_regs;
790     IDEState *ide_state;
791     SDBFIS *sdb_fis;
792 
793     if (!ad->res_fis ||
794         !(pr->cmd & PORT_CMD_FIS_RX)) {
795         return;
796     }
797 
798     sdb_fis = (SDBFIS *)&ad->res_fis[RES_FIS_SDBFIS];
799     ide_state = &ad->port.ifs[0];
800 
801     sdb_fis->type = SATA_FIS_TYPE_SDB;
802     /* Interrupt pending & Notification bit */
803     sdb_fis->flags = 0x40; /* Interrupt bit, always 1 for NCQ */
804     sdb_fis->status = ide_state->status & 0x77;
805     sdb_fis->error = ide_state->error;
806     /* update SAct field in SDB_FIS */
807     sdb_fis->payload = cpu_to_le32(ad->finished);
808 
809     /* Update shadow registers (except BSY 0x80 and DRQ 0x08) */
810     pr->tfdata = (ad->port.ifs[0].error << 8) |
811         (ad->port.ifs[0].status & 0x77) |
812         (pr->tfdata & 0x88);
813     pr->scr_act &= ~ad->finished;
814     ad->finished = 0;
815 
816     /*
817      * TFES IRQ is always raised if ERR_STAT is set, regardless of I bit.
818      * If ERR_STAT is not set, trigger SDBS IRQ if interrupt bit is set
819      * (which currently, it always is).
820      */
821     if (sdb_fis->status & ERR_STAT) {
822         ahci_trigger_irq(s, ad, AHCI_PORT_IRQ_BIT_TFES);
823     } else if (sdb_fis->flags & 0x40) {
824         ahci_trigger_irq(s, ad, AHCI_PORT_IRQ_BIT_SDBS);
825     }
826 }
827 
828 static void ahci_write_fis_pio(AHCIDevice *ad, uint16_t len, bool pio_fis_i)
829 {
830     AHCIPortRegs *pr = &ad->port_regs;
831     uint8_t *pio_fis;
832     IDEState *s = &ad->port.ifs[0];
833 
834     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
835         return;
836     }
837 
838     pio_fis = &ad->res_fis[RES_FIS_PSFIS];
839 
840     pio_fis[0] = SATA_FIS_TYPE_PIO_SETUP;
841     pio_fis[1] = (pio_fis_i ? (1 << 6) : 0);
842     pio_fis[2] = s->status;
843     pio_fis[3] = s->error;
844 
845     pio_fis[4] = s->sector;
846     pio_fis[5] = s->lcyl;
847     pio_fis[6] = s->hcyl;
848     pio_fis[7] = s->select;
849     pio_fis[8] = s->hob_sector;
850     pio_fis[9] = s->hob_lcyl;
851     pio_fis[10] = s->hob_hcyl;
852     pio_fis[11] = 0;
853     pio_fis[12] = s->nsector & 0xFF;
854     pio_fis[13] = (s->nsector >> 8) & 0xFF;
855     pio_fis[14] = 0;
856     pio_fis[15] = s->status;
857     pio_fis[16] = len & 255;
858     pio_fis[17] = len >> 8;
859     pio_fis[18] = 0;
860     pio_fis[19] = 0;
861 
862     /* Update shadow registers: */
863     pr->tfdata = (ad->port.ifs[0].error << 8) |
864         ad->port.ifs[0].status;
865 
866     if (pio_fis[2] & ERR_STAT) {
867         ahci_trigger_irq(ad->hba, ad, AHCI_PORT_IRQ_BIT_TFES);
868     }
869 }
870 
871 static bool ahci_write_fis_d2h(AHCIDevice *ad, bool d2h_fis_i)
872 {
873     AHCIPortRegs *pr = &ad->port_regs;
874     uint8_t *d2h_fis;
875     int i;
876     IDEState *s = &ad->port.ifs[0];
877 
878     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
879         return false;
880     }
881 
882     d2h_fis = &ad->res_fis[RES_FIS_RFIS];
883 
884     d2h_fis[0] = SATA_FIS_TYPE_REGISTER_D2H;
885     d2h_fis[1] = d2h_fis_i ? (1 << 6) : 0; /* interrupt bit */
886     d2h_fis[2] = s->status;
887     d2h_fis[3] = s->error;
888 
889     d2h_fis[4] = s->sector;
890     d2h_fis[5] = s->lcyl;
891     d2h_fis[6] = s->hcyl;
892     d2h_fis[7] = s->select;
893     d2h_fis[8] = s->hob_sector;
894     d2h_fis[9] = s->hob_lcyl;
895     d2h_fis[10] = s->hob_hcyl;
896     d2h_fis[11] = 0;
897     d2h_fis[12] = s->nsector & 0xFF;
898     d2h_fis[13] = (s->nsector >> 8) & 0xFF;
899     for (i = 14; i < 20; i++) {
900         d2h_fis[i] = 0;
901     }
902 
903     /* Update shadow registers: */
904     pr->tfdata = (ad->port.ifs[0].error << 8) |
905         ad->port.ifs[0].status;
906 
907     /* TFES IRQ is always raised if ERR_STAT is set, regardless of I bit. */
908     if (d2h_fis[2] & ERR_STAT) {
909         ahci_trigger_irq(ad->hba, ad, AHCI_PORT_IRQ_BIT_TFES);
910     } else if (d2h_fis_i) {
911         ahci_trigger_irq(ad->hba, ad, AHCI_PORT_IRQ_BIT_DHRS);
912     }
913 
914     return true;
915 }
916 
917 static int prdt_tbl_entry_size(const AHCI_SG *tbl)
918 {
919     /* flags_size is zero-based */
920     return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1;
921 }
922 
923 /**
924  * Fetch entries in a guest-provided PRDT and convert it into a QEMU SGlist.
925  * @ad: The AHCIDevice for whom we are building the SGList.
926  * @sglist: The SGList target to add PRD entries to.
927  * @cmd: The AHCI Command Header that describes where the PRDT is.
928  * @limit: The remaining size of the S/ATA transaction, in bytes.
929  * @offset: The number of bytes already transferred, in bytes.
930  *
931  * The AHCI PRDT can describe up to 256GiB. S/ATA only support transactions of
932  * up to 32MiB as of ATA8-ACS3 rev 1b, assuming a 512 byte sector size. We stop
933  * building the sglist from the PRDT as soon as we hit @limit bytes,
934  * which is <= INT32_MAX/2GiB.
935  */
936 static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist,
937                                 AHCICmdHdr *cmd, int64_t limit, uint64_t offset)
938 {
939     uint16_t opts = le16_to_cpu(cmd->opts);
940     uint16_t prdtl = le16_to_cpu(cmd->prdtl);
941     uint64_t cfis_addr = le64_to_cpu(cmd->tbl_addr);
942     uint64_t prdt_addr = cfis_addr + 0x80;
943     dma_addr_t prdt_len = (prdtl * sizeof(AHCI_SG));
944     dma_addr_t real_prdt_len = prdt_len;
945     uint8_t *prdt;
946     int i;
947     int r = 0;
948     uint64_t sum = 0;
949     int off_idx = -1;
950     int64_t off_pos = -1;
951     int tbl_entry_size;
952     IDEBus *bus = &ad->port;
953     BusState *qbus = BUS(bus);
954 
955     trace_ahci_populate_sglist(ad->hba, ad->port_no);
956 
957     if (!prdtl) {
958         trace_ahci_populate_sglist_no_prdtl(ad->hba, ad->port_no, opts);
959         return -1;
960     }
961 
962     /* map PRDT */
963     if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,
964                                 DMA_DIRECTION_TO_DEVICE,
965                                 MEMTXATTRS_UNSPECIFIED))){
966         trace_ahci_populate_sglist_no_map(ad->hba, ad->port_no);
967         return -1;
968     }
969 
970     if (prdt_len < real_prdt_len) {
971         trace_ahci_populate_sglist_short_map(ad->hba, ad->port_no);
972         r = -1;
973         goto out;
974     }
975 
976     /* Get entries in the PRDT, init a qemu sglist accordingly */
977     if (prdtl > 0) {
978         AHCI_SG *tbl = (AHCI_SG *)prdt;
979         sum = 0;
980         for (i = 0; i < prdtl; i++) {
981             tbl_entry_size = prdt_tbl_entry_size(&tbl[i]);
982             if (offset < (sum + tbl_entry_size)) {
983                 off_idx = i;
984                 off_pos = offset - sum;
985                 break;
986             }
987             sum += tbl_entry_size;
988         }
989         if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {
990             trace_ahci_populate_sglist_bad_offset(ad->hba, ad->port_no,
991                                                   off_idx, off_pos);
992             r = -1;
993             goto out;
994         }
995 
996         qemu_sglist_init(sglist, qbus->parent, (prdtl - off_idx),
997                          ad->hba->as);
998         qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr) + off_pos,
999                         MIN(prdt_tbl_entry_size(&tbl[off_idx]) - off_pos,
1000                             limit));
1001 
1002         for (i = off_idx + 1; i < prdtl && sglist->size < limit; i++) {
1003             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
1004                             MIN(prdt_tbl_entry_size(&tbl[i]),
1005                                 limit - sglist->size));
1006         }
1007     }
1008 
1009 out:
1010     dma_memory_unmap(ad->hba->as, prdt, prdt_len,
1011                      DMA_DIRECTION_TO_DEVICE, prdt_len);
1012     return r;
1013 }
1014 
1015 static void ncq_err(NCQTransferState *ncq_tfs)
1016 {
1017     IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
1018 
1019     ide_state->error = ABRT_ERR;
1020     ide_state->status = READY_STAT | ERR_STAT;
1021     qemu_sglist_destroy(&ncq_tfs->sglist);
1022     ncq_tfs->used = 0;
1023 }
1024 
1025 static void ncq_finish(NCQTransferState *ncq_tfs)
1026 {
1027     /* If we didn't error out, set our finished bit. Errored commands
1028      * do not get a bit set for the SDB FIS ACT register, nor do they
1029      * clear the outstanding bit in scr_act (PxSACT). */
1030     if (ncq_tfs->used) {
1031         ncq_tfs->drive->finished |= (1 << ncq_tfs->tag);
1032     }
1033 
1034     ahci_write_fis_sdb(ncq_tfs->drive->hba, ncq_tfs);
1035 
1036     trace_ncq_finish(ncq_tfs->drive->hba, ncq_tfs->drive->port_no,
1037                      ncq_tfs->tag);
1038 
1039     block_acct_done(blk_get_stats(ncq_tfs->drive->port.ifs[0].blk),
1040                     &ncq_tfs->acct);
1041     qemu_sglist_destroy(&ncq_tfs->sglist);
1042     ncq_tfs->used = 0;
1043 }
1044 
1045 static void ncq_cb(void *opaque, int ret)
1046 {
1047     NCQTransferState *ncq_tfs = (NCQTransferState *)opaque;
1048     IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
1049 
1050     ncq_tfs->aiocb = NULL;
1051 
1052     if (ret < 0) {
1053         bool is_read = ncq_tfs->cmd == READ_FPDMA_QUEUED;
1054         BlockErrorAction action = blk_get_error_action(ide_state->blk,
1055                                                        is_read, -ret);
1056         if (action == BLOCK_ERROR_ACTION_STOP) {
1057             ncq_tfs->halt = true;
1058             ide_state->bus->error_status = IDE_RETRY_HBA;
1059         } else if (action == BLOCK_ERROR_ACTION_REPORT) {
1060             ncq_err(ncq_tfs);
1061         }
1062         blk_error_action(ide_state->blk, action, is_read, -ret);
1063     } else {
1064         ide_state->status = READY_STAT | SEEK_STAT;
1065     }
1066 
1067     if (!ncq_tfs->halt) {
1068         ncq_finish(ncq_tfs);
1069     }
1070 }
1071 
1072 static int is_ncq(uint8_t ata_cmd)
1073 {
1074     /* Based on SATA 3.2 section 13.6.3.2 */
1075     switch (ata_cmd) {
1076     case READ_FPDMA_QUEUED:
1077     case WRITE_FPDMA_QUEUED:
1078     case NCQ_NON_DATA:
1079     case RECEIVE_FPDMA_QUEUED:
1080     case SEND_FPDMA_QUEUED:
1081         return 1;
1082     default:
1083         return 0;
1084     }
1085 }
1086 
1087 static void execute_ncq_command(NCQTransferState *ncq_tfs)
1088 {
1089     AHCIDevice *ad = ncq_tfs->drive;
1090     IDEState *ide_state = &ad->port.ifs[0];
1091     int port = ad->port_no;
1092 
1093     g_assert(is_ncq(ncq_tfs->cmd));
1094     ncq_tfs->halt = false;
1095 
1096     switch (ncq_tfs->cmd) {
1097     case READ_FPDMA_QUEUED:
1098         trace_execute_ncq_command_read(ad->hba, port, ncq_tfs->tag,
1099                                        ncq_tfs->sector_count, ncq_tfs->lba);
1100         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1101                        &ncq_tfs->sglist, BLOCK_ACCT_READ);
1102         ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
1103                                       ncq_tfs->lba << BDRV_SECTOR_BITS,
1104                                       BDRV_SECTOR_SIZE,
1105                                       ncq_cb, ncq_tfs);
1106         break;
1107     case WRITE_FPDMA_QUEUED:
1108         trace_execute_ncq_command_write(ad->hba, port, ncq_tfs->tag,
1109                                         ncq_tfs->sector_count, ncq_tfs->lba);
1110         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1111                        &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
1112         ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
1113                                        ncq_tfs->lba << BDRV_SECTOR_BITS,
1114                                        BDRV_SECTOR_SIZE,
1115                                        ncq_cb, ncq_tfs);
1116         break;
1117     default:
1118         trace_execute_ncq_command_unsup(ad->hba, port,
1119                                         ncq_tfs->tag, ncq_tfs->cmd);
1120         ncq_err(ncq_tfs);
1121     }
1122 }
1123 
1124 
1125 static void process_ncq_command(AHCIState *s, int port, const uint8_t *cmd_fis,
1126                                 uint8_t slot)
1127 {
1128     AHCIDevice *ad = &s->dev[port];
1129     const NCQFrame *ncq_fis = (NCQFrame *)cmd_fis;
1130     uint8_t tag = ncq_fis->tag >> 3;
1131     NCQTransferState *ncq_tfs = &ad->ncq_tfs[tag];
1132     size_t size;
1133 
1134     g_assert(is_ncq(ncq_fis->command));
1135     if (ncq_tfs->used) {
1136         /* error - already in use */
1137         qemu_log_mask(LOG_GUEST_ERROR, "%s: tag %d already used\n",
1138                       __func__, tag);
1139         return;
1140     }
1141 
1142     /*
1143      * A NCQ command clears the bit in PxCI after the command has been QUEUED
1144      * successfully (ERROR not set, BUSY and DRQ cleared).
1145      *
1146      * For NCQ commands, PxCI will always be cleared here.
1147      *
1148      * (Once the NCQ command is COMPLETED, the device will send a SDB FIS with
1149      * the interrupt bit set, which will clear PxSACT and raise an interrupt.)
1150      */
1151     ahci_clear_cmd_issue(ad, slot);
1152 
1153     /*
1154      * In reality, for NCQ commands, PxCI is cleared after receiving a D2H FIS
1155      * without the interrupt bit set, but since ahci_write_fis_d2h() can raise
1156      * an IRQ on error, we need to call them in reverse order.
1157      */
1158     ahci_write_fis_d2h(ad, false);
1159 
1160     ncq_tfs->used = 1;
1161     ncq_tfs->drive = ad;
1162     ncq_tfs->slot = slot;
1163     ncq_tfs->cmdh = &((AHCICmdHdr *)ad->lst)[slot];
1164     ncq_tfs->cmd = ncq_fis->command;
1165     ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
1166                    ((uint64_t)ncq_fis->lba4 << 32) |
1167                    ((uint64_t)ncq_fis->lba3 << 24) |
1168                    ((uint64_t)ncq_fis->lba2 << 16) |
1169                    ((uint64_t)ncq_fis->lba1 << 8) |
1170                    (uint64_t)ncq_fis->lba0;
1171     ncq_tfs->tag = tag;
1172 
1173     /* Sanity-check the NCQ packet */
1174     if (tag != slot) {
1175         trace_process_ncq_command_mismatch(s, port, tag, slot);
1176     }
1177 
1178     if (ncq_fis->aux0 || ncq_fis->aux1 || ncq_fis->aux2 || ncq_fis->aux3) {
1179         trace_process_ncq_command_aux(s, port, tag);
1180     }
1181     if (ncq_fis->prio || ncq_fis->icc) {
1182         trace_process_ncq_command_prioicc(s, port, tag);
1183     }
1184     if (ncq_fis->fua & NCQ_FIS_FUA_MASK) {
1185         trace_process_ncq_command_fua(s, port, tag);
1186     }
1187     if (ncq_fis->tag & NCQ_FIS_RARC_MASK) {
1188         trace_process_ncq_command_rarc(s, port, tag);
1189     }
1190 
1191     ncq_tfs->sector_count = ((ncq_fis->sector_count_high << 8) |
1192                              ncq_fis->sector_count_low);
1193     if (!ncq_tfs->sector_count) {
1194         ncq_tfs->sector_count = 0x10000;
1195     }
1196     size = ncq_tfs->sector_count * BDRV_SECTOR_SIZE;
1197     ahci_populate_sglist(ad, &ncq_tfs->sglist, ncq_tfs->cmdh, size, 0);
1198 
1199     if (ncq_tfs->sglist.size < size) {
1200         error_report("ahci: PRDT length for NCQ command (0x" DMA_ADDR_FMT ") "
1201                      "is smaller than the requested size (0x%zx)",
1202                      ncq_tfs->sglist.size, size);
1203         ncq_err(ncq_tfs);
1204         ahci_trigger_irq(ad->hba, ad, AHCI_PORT_IRQ_BIT_OFS);
1205         return;
1206     } else if (ncq_tfs->sglist.size != size) {
1207         trace_process_ncq_command_large(s, port, tag,
1208                                         ncq_tfs->sglist.size, size);
1209     }
1210 
1211     trace_process_ncq_command(s, port, tag,
1212                               ncq_fis->command,
1213                               ncq_tfs->lba,
1214                               ncq_tfs->lba + ncq_tfs->sector_count - 1);
1215     execute_ncq_command(ncq_tfs);
1216 }
1217 
1218 static AHCICmdHdr *get_cmd_header(AHCIState *s, uint8_t port, uint8_t slot)
1219 {
1220     if (port >= s->ports || slot >= AHCI_MAX_CMDS) {
1221         return NULL;
1222     }
1223 
1224     return s->dev[port].lst ? &((AHCICmdHdr *)s->dev[port].lst)[slot] : NULL;
1225 }
1226 
1227 static void handle_reg_h2d_fis(AHCIState *s, int port,
1228                                uint8_t slot, const uint8_t *cmd_fis)
1229 {
1230     IDEState *ide_state = &s->dev[port].port.ifs[0];
1231     AHCICmdHdr *cmd = get_cmd_header(s, port, slot);
1232     AHCIDevice *ad = &s->dev[port];
1233     uint16_t opts = le16_to_cpu(cmd->opts);
1234 
1235     if (cmd_fis[1] & 0x0F) {
1236         trace_handle_reg_h2d_fis_pmp(s, port, cmd_fis[1],
1237                                      cmd_fis[2], cmd_fis[3]);
1238         return;
1239     }
1240 
1241     if (cmd_fis[1] & 0x70) {
1242         trace_handle_reg_h2d_fis_res(s, port, cmd_fis[1],
1243                                      cmd_fis[2], cmd_fis[3]);
1244         return;
1245     }
1246 
1247     if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {
1248         switch (s->dev[port].port_state) {
1249         case STATE_RUN:
1250             if (cmd_fis[15] & ATA_SRST) {
1251                 s->dev[port].port_state = STATE_RESET;
1252                 /*
1253                  * When setting SRST in the first H2D FIS in the reset sequence,
1254                  * the device does not send a D2H FIS. Host software thus has to
1255                  * set the "Clear Busy upon R_OK" bit such that PxCI (and BUSY)
1256                  * gets cleared. See AHCI 1.3.1, section 10.4.1 Software Reset.
1257                  */
1258                 if (opts & AHCI_CMD_CLR_BUSY) {
1259                     ahci_clear_cmd_issue(ad, slot);
1260                 }
1261             }
1262             break;
1263         case STATE_RESET:
1264             if (!(cmd_fis[15] & ATA_SRST)) {
1265                 /*
1266                  * When clearing SRST in the second H2D FIS in the reset
1267                  * sequence, the device will execute diagnostics. When this is
1268                  * done, the device will send a D2H FIS with the good status.
1269                  * See SATA 3.5a Gold, section 11.4 Software reset protocol.
1270                  *
1271                  * This D2H FIS is the first D2H FIS received from the device,
1272                  * and is received regardless if the reset was performed by a
1273                  * COMRESET or by setting and clearing the SRST bit. Therefore,
1274                  * the logic for this is found in ahci_init_d2h() and not here.
1275                  */
1276                 ahci_reset_port(s, port);
1277             }
1278             break;
1279         }
1280         return;
1281     }
1282 
1283     /* Check for NCQ command */
1284     if (is_ncq(cmd_fis[2])) {
1285         process_ncq_command(s, port, cmd_fis, slot);
1286         return;
1287     }
1288 
1289     /* Decompose the FIS:
1290      * AHCI does not interpret FIS packets, it only forwards them.
1291      * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.
1292      * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.
1293      *
1294      * ATA4 describes sector number for LBA28/CHS commands.
1295      * ATA6 describes sector number for LBA48 commands.
1296      * ATA8 deprecates CHS fully, describing only LBA28/48.
1297      *
1298      * We dutifully convert the FIS into IDE registers, and allow the
1299      * core layer to interpret them as needed. */
1300     ide_state->feature = cmd_fis[3];
1301     ide_state->sector = cmd_fis[4];      /* LBA 7:0 */
1302     ide_state->lcyl = cmd_fis[5];        /* LBA 15:8  */
1303     ide_state->hcyl = cmd_fis[6];        /* LBA 23:16 */
1304     ide_state->select = cmd_fis[7];      /* LBA 27:24 (LBA28) */
1305     ide_state->hob_sector = cmd_fis[8];  /* LBA 31:24 */
1306     ide_state->hob_lcyl = cmd_fis[9];    /* LBA 39:32 */
1307     ide_state->hob_hcyl = cmd_fis[10];   /* LBA 47:40 */
1308     ide_state->hob_feature = cmd_fis[11];
1309     ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
1310     /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */
1311     /* 15: Only valid when UPDATE_COMMAND not set. */
1312 
1313     /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
1314      * table to ide_state->io_buffer */
1315     if (opts & AHCI_CMD_ATAPI) {
1316         memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
1317         if (trace_event_get_state_backends(TRACE_HANDLE_REG_H2D_FIS_DUMP)) {
1318             char *pretty_fis = ahci_pretty_buffer_fis(ide_state->io_buffer, 0x10);
1319             trace_handle_reg_h2d_fis_dump(s, port, pretty_fis);
1320             g_free(pretty_fis);
1321         }
1322     }
1323 
1324     ide_state->error = 0;
1325     s->dev[port].done_first_drq = false;
1326     /* Reset transferred byte counter */
1327     cmd->status = 0;
1328 
1329     /*
1330      * A non-NCQ command clears the bit in PxCI after the command has COMPLETED
1331      * successfully (ERROR not set, BUSY and DRQ cleared).
1332      *
1333      * For non-NCQ commands, PxCI will always be cleared by ahci_cmd_done().
1334      */
1335     ad->busy_slot = slot;
1336 
1337     /* We're ready to process the command in FIS byte 2. */
1338     ide_bus_exec_cmd(&s->dev[port].port, cmd_fis[2]);
1339 }
1340 
1341 static void handle_cmd(AHCIState *s, int port, uint8_t slot)
1342 {
1343     IDEState *ide_state;
1344     uint64_t tbl_addr;
1345     AHCICmdHdr *cmd;
1346     uint8_t *cmd_fis;
1347     dma_addr_t cmd_len;
1348 
1349     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1350         /* Engine currently busy, try again later */
1351         trace_handle_cmd_busy(s, port);
1352         return;
1353     }
1354 
1355     if (!s->dev[port].lst) {
1356         trace_handle_cmd_nolist(s, port);
1357         return;
1358     }
1359     cmd = get_cmd_header(s, port, slot);
1360     /* remember current slot handle for later */
1361     s->dev[port].cur_cmd = cmd;
1362 
1363     /* The device we are working for */
1364     ide_state = &s->dev[port].port.ifs[0];
1365     if (!ide_state->blk) {
1366         trace_handle_cmd_badport(s, port);
1367         return;
1368     }
1369 
1370     tbl_addr = le64_to_cpu(cmd->tbl_addr);
1371     cmd_len = 0x80;
1372     cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,
1373                              DMA_DIRECTION_TO_DEVICE, MEMTXATTRS_UNSPECIFIED);
1374     if (!cmd_fis) {
1375         trace_handle_cmd_badfis(s, port);
1376         return;
1377     } else if (cmd_len != 0x80) {
1378         ahci_trigger_irq(s, &s->dev[port], AHCI_PORT_IRQ_BIT_HBFS);
1379         trace_handle_cmd_badmap(s, port, cmd_len);
1380         goto out;
1381     }
1382     if (trace_event_get_state_backends(TRACE_HANDLE_CMD_FIS_DUMP)) {
1383         char *pretty_fis = ahci_pretty_buffer_fis(cmd_fis, 0x80);
1384         trace_handle_cmd_fis_dump(s, port, pretty_fis);
1385         g_free(pretty_fis);
1386     }
1387     switch (cmd_fis[0]) {
1388         case SATA_FIS_TYPE_REGISTER_H2D:
1389             handle_reg_h2d_fis(s, port, slot, cmd_fis);
1390             break;
1391         default:
1392             trace_handle_cmd_unhandled_fis(s, port,
1393                                            cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1394             break;
1395     }
1396 
1397 out:
1398     dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_TO_DEVICE,
1399                      cmd_len);
1400 }
1401 
1402 /* Transfer PIO data between RAM and device */
1403 static void ahci_pio_transfer(const IDEDMA *dma)
1404 {
1405     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1406     IDEState *s = &ad->port.ifs[0];
1407     uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
1408     /* write == ram -> device */
1409     uint16_t opts = le16_to_cpu(ad->cur_cmd->opts);
1410     int is_write = opts & AHCI_CMD_WRITE;
1411     int is_atapi = opts & AHCI_CMD_ATAPI;
1412     int has_sglist = 0;
1413     bool pio_fis_i;
1414 
1415     /* The PIO Setup FIS is received prior to transfer, but the interrupt
1416      * is only triggered after data is received.
1417      *
1418      * The device only sets the 'I' bit in the PIO Setup FIS for device->host
1419      * requests (see "DPIOI1" in the SATA spec), or for host->device DRQs after
1420      * the first (see "DPIOO1").  The latter is consistent with the spec's
1421      * description of the PACKET protocol, where the command part of ATAPI requests
1422      * ("DPKT0") has the 'I' bit clear, while the data part of PIO ATAPI requests
1423      * ("DPKT4a" and "DPKT7") has the 'I' bit set for both directions for all DRQs.
1424      */
1425     pio_fis_i = ad->done_first_drq || (!is_atapi && !is_write);
1426     ahci_write_fis_pio(ad, size, pio_fis_i);
1427 
1428     if (is_atapi && !ad->done_first_drq) {
1429         /* already prepopulated iobuffer */
1430         goto out;
1431     }
1432 
1433     if (ahci_dma_prepare_buf(dma, size)) {
1434         has_sglist = 1;
1435     }
1436 
1437     trace_ahci_pio_transfer(ad->hba, ad->port_no, is_write ? "writ" : "read",
1438                             size, is_atapi ? "atapi" : "ata",
1439                             has_sglist ? "" : "o");
1440 
1441     if (has_sglist && size) {
1442         const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
1443 
1444         if (is_write) {
1445             dma_buf_write(s->data_ptr, size, NULL, &s->sg, attrs);
1446         } else {
1447             dma_buf_read(s->data_ptr, size, NULL, &s->sg, attrs);
1448         }
1449     }
1450 
1451     /* Update number of transferred bytes, destroy sglist */
1452     dma_buf_commit(s, size);
1453 
1454 out:
1455     /* declare that we processed everything */
1456     s->data_ptr = s->data_end;
1457 
1458     ad->done_first_drq = true;
1459     if (pio_fis_i) {
1460         ahci_trigger_irq(ad->hba, ad, AHCI_PORT_IRQ_BIT_PSS);
1461     }
1462 }
1463 
1464 static void ahci_start_dma(const IDEDMA *dma, IDEState *s,
1465                            BlockCompletionFunc *dma_cb)
1466 {
1467     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1468     trace_ahci_start_dma(ad->hba, ad->port_no);
1469     s->io_buffer_offset = 0;
1470     dma_cb(s, 0);
1471 }
1472 
1473 static void ahci_restart_dma(const IDEDMA *dma)
1474 {
1475     /* Nothing to do, ahci_start_dma already resets s->io_buffer_offset.  */
1476 }
1477 
1478 /**
1479  * IDE/PIO restarts are handled by the core layer, but NCQ commands
1480  * need an extra kick from the AHCI HBA.
1481  */
1482 static void ahci_restart(const IDEDMA *dma)
1483 {
1484     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1485     int i;
1486 
1487     for (i = 0; i < AHCI_MAX_CMDS; i++) {
1488         NCQTransferState *ncq_tfs = &ad->ncq_tfs[i];
1489         if (ncq_tfs->halt) {
1490             execute_ncq_command(ncq_tfs);
1491         }
1492     }
1493 }
1494 
1495 /**
1496  * Called in DMA and PIO R/W chains to read the PRDT.
1497  * Not shared with NCQ pathways.
1498  */
1499 static int32_t ahci_dma_prepare_buf(const IDEDMA *dma, int32_t limit)
1500 {
1501     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1502     IDEState *s = &ad->port.ifs[0];
1503 
1504     if (ahci_populate_sglist(ad, &s->sg, ad->cur_cmd,
1505                              limit, s->io_buffer_offset) == -1) {
1506         trace_ahci_dma_prepare_buf_fail(ad->hba, ad->port_no);
1507         return -1;
1508     }
1509     s->io_buffer_size = s->sg.size;
1510 
1511     trace_ahci_dma_prepare_buf(ad->hba, ad->port_no, limit, s->io_buffer_size);
1512     return s->io_buffer_size;
1513 }
1514 
1515 /**
1516  * Updates the command header with a bytes-read value.
1517  * Called via dma_buf_commit, for both DMA and PIO paths.
1518  * sglist destruction is handled within dma_buf_commit.
1519  */
1520 static void ahci_commit_buf(const IDEDMA *dma, uint32_t tx_bytes)
1521 {
1522     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1523 
1524     tx_bytes += le32_to_cpu(ad->cur_cmd->status);
1525     ad->cur_cmd->status = cpu_to_le32(tx_bytes);
1526 }
1527 
1528 static int ahci_dma_rw_buf(const IDEDMA *dma, bool is_write)
1529 {
1530     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1531     IDEState *s = &ad->port.ifs[0];
1532     uint8_t *p = s->io_buffer + s->io_buffer_index;
1533     int l = s->io_buffer_size - s->io_buffer_index;
1534 
1535     if (ahci_populate_sglist(ad, &s->sg, ad->cur_cmd, l, s->io_buffer_offset)) {
1536         return 0;
1537     }
1538 
1539     if (is_write) {
1540         dma_buf_read(p, l, NULL, &s->sg, MEMTXATTRS_UNSPECIFIED);
1541     } else {
1542         dma_buf_write(p, l, NULL, &s->sg, MEMTXATTRS_UNSPECIFIED);
1543     }
1544 
1545     /* free sglist, update byte count */
1546     dma_buf_commit(s, l);
1547     s->io_buffer_index += l;
1548 
1549     trace_ahci_dma_rw_buf(ad->hba, ad->port_no, l);
1550     return 1;
1551 }
1552 
1553 static void ahci_clear_cmd_issue(AHCIDevice *ad, uint8_t slot)
1554 {
1555     IDEState *ide_state = &ad->port.ifs[0];
1556 
1557     if (!(ide_state->status & ERR_STAT) &&
1558         !(ide_state->status & (BUSY_STAT | DRQ_STAT))) {
1559         ad->port_regs.cmd_issue &= ~(1 << slot);
1560     }
1561 }
1562 
1563 /* Non-NCQ command is done - This function is never called for NCQ commands. */
1564 static void ahci_cmd_done(const IDEDMA *dma)
1565 {
1566     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1567     IDEState *ide_state = &ad->port.ifs[0];
1568 
1569     trace_ahci_cmd_done(ad->hba, ad->port_no);
1570 
1571     /* no longer busy */
1572     if (ad->busy_slot != -1) {
1573         ahci_clear_cmd_issue(ad, ad->busy_slot);
1574         ad->busy_slot = -1;
1575     }
1576 
1577     /*
1578      * In reality, for non-NCQ commands, PxCI is cleared after receiving a D2H
1579      * FIS with the interrupt bit set, but since ahci_write_fis_d2h() will raise
1580      * an IRQ, we need to call them in reverse order.
1581      */
1582     ahci_write_fis_d2h(ad, true);
1583 
1584     if (!(ide_state->status & ERR_STAT) &&
1585         ad->port_regs.cmd_issue && !ad->check_bh) {
1586         ad->check_bh = qemu_bh_new_guarded(ahci_check_cmd_bh, ad,
1587                                            &ad->mem_reentrancy_guard);
1588         qemu_bh_schedule(ad->check_bh);
1589     }
1590 }
1591 
1592 static void ahci_irq_set(void *opaque, int n, int level)
1593 {
1594     qemu_log_mask(LOG_UNIMP, "ahci: IRQ#%d level:%d\n", n, level);
1595 }
1596 
1597 static const IDEDMAOps ahci_dma_ops = {
1598     .start_dma = ahci_start_dma,
1599     .restart = ahci_restart,
1600     .restart_dma = ahci_restart_dma,
1601     .pio_transfer = ahci_pio_transfer,
1602     .prepare_buf = ahci_dma_prepare_buf,
1603     .commit_buf = ahci_commit_buf,
1604     .rw_buf = ahci_dma_rw_buf,
1605     .cmd_done = ahci_cmd_done,
1606 };
1607 
1608 void ahci_init(AHCIState *s, DeviceState *qdev)
1609 {
1610     s->container = qdev;
1611     /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1612     memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s,
1613                           "ahci", AHCI_MEM_BAR_SIZE);
1614     memory_region_init_io(&s->idp, OBJECT(qdev), &ahci_idp_ops, s,
1615                           "ahci-idp", 32);
1616 }
1617 
1618 void ahci_realize(AHCIState *s, DeviceState *qdev, AddressSpace *as)
1619 {
1620     qemu_irq *irqs;
1621     int i;
1622 
1623     s->as = as;
1624     assert(s->ports > 0);
1625     s->dev = g_new0(AHCIDevice, s->ports);
1626     ahci_reg_init(s);
1627     irqs = qemu_allocate_irqs(ahci_irq_set, s, s->ports);
1628     for (i = 0; i < s->ports; i++) {
1629         AHCIDevice *ad = &s->dev[i];
1630 
1631         ide_bus_init(&ad->port, sizeof(ad->port), qdev, i, 1);
1632         ide_bus_init_output_irq(&ad->port, irqs[i]);
1633 
1634         ad->hba = s;
1635         ad->port_no = i;
1636         ad->port.dma = &ad->dma;
1637         ad->port.dma->ops = &ahci_dma_ops;
1638         ide_bus_register_restart_cb(&ad->port);
1639     }
1640     g_free(irqs);
1641 }
1642 
1643 void ahci_uninit(AHCIState *s)
1644 {
1645     int i, j;
1646 
1647     for (i = 0; i < s->ports; i++) {
1648         AHCIDevice *ad = &s->dev[i];
1649 
1650         for (j = 0; j < 2; j++) {
1651             ide_exit(&ad->port.ifs[j]);
1652         }
1653         object_unparent(OBJECT(&ad->port));
1654     }
1655 
1656     g_free(s->dev);
1657 }
1658 
1659 void ahci_reset(AHCIState *s)
1660 {
1661     AHCIPortRegs *pr;
1662     int i;
1663 
1664     trace_ahci_reset(s);
1665 
1666     s->control_regs.irqstatus = 0;
1667     /* AHCI Enable (AE)
1668      * The implementation of this bit is dependent upon the value of the
1669      * CAP.SAM bit. If CAP.SAM is '0', then GHC.AE shall be read-write and
1670      * shall have a reset value of '0'. If CAP.SAM is '1', then AE shall be
1671      * read-only and shall have a reset value of '1'.
1672      *
1673      * We set HOST_CAP_AHCI so we must enable AHCI at reset.
1674      */
1675     s->control_regs.ghc = HOST_CTL_AHCI_EN;
1676 
1677     for (i = 0; i < s->ports; i++) {
1678         pr = &s->dev[i].port_regs;
1679         pr->irq_stat = 0;
1680         pr->irq_mask = 0;
1681         pr->scr_ctl = 0;
1682         pr->cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
1683         ahci_reset_port(s, i);
1684     }
1685 }
1686 
1687 static const VMStateDescription vmstate_ncq_tfs = {
1688     .name = "ncq state",
1689     .version_id = 1,
1690     .fields = (const VMStateField[]) {
1691         VMSTATE_UINT32(sector_count, NCQTransferState),
1692         VMSTATE_UINT64(lba, NCQTransferState),
1693         VMSTATE_UINT8(tag, NCQTransferState),
1694         VMSTATE_UINT8(cmd, NCQTransferState),
1695         VMSTATE_UINT8(slot, NCQTransferState),
1696         VMSTATE_BOOL(used, NCQTransferState),
1697         VMSTATE_BOOL(halt, NCQTransferState),
1698         VMSTATE_END_OF_LIST()
1699     },
1700 };
1701 
1702 static const VMStateDescription vmstate_ahci_device = {
1703     .name = "ahci port",
1704     .version_id = 1,
1705     .fields = (const VMStateField[]) {
1706         VMSTATE_IDE_BUS(port, AHCIDevice),
1707         VMSTATE_IDE_DRIVE(port.ifs[0], AHCIDevice),
1708         VMSTATE_UINT32(port_state, AHCIDevice),
1709         VMSTATE_UINT32(finished, AHCIDevice),
1710         VMSTATE_UINT32(port_regs.lst_addr, AHCIDevice),
1711         VMSTATE_UINT32(port_regs.lst_addr_hi, AHCIDevice),
1712         VMSTATE_UINT32(port_regs.fis_addr, AHCIDevice),
1713         VMSTATE_UINT32(port_regs.fis_addr_hi, AHCIDevice),
1714         VMSTATE_UINT32(port_regs.irq_stat, AHCIDevice),
1715         VMSTATE_UINT32(port_regs.irq_mask, AHCIDevice),
1716         VMSTATE_UINT32(port_regs.cmd, AHCIDevice),
1717         VMSTATE_UINT32(port_regs.tfdata, AHCIDevice),
1718         VMSTATE_UINT32(port_regs.sig, AHCIDevice),
1719         VMSTATE_UINT32(port_regs.scr_stat, AHCIDevice),
1720         VMSTATE_UINT32(port_regs.scr_ctl, AHCIDevice),
1721         VMSTATE_UINT32(port_regs.scr_err, AHCIDevice),
1722         VMSTATE_UINT32(port_regs.scr_act, AHCIDevice),
1723         VMSTATE_UINT32(port_regs.cmd_issue, AHCIDevice),
1724         VMSTATE_BOOL(done_first_drq, AHCIDevice),
1725         VMSTATE_INT32(busy_slot, AHCIDevice),
1726         VMSTATE_BOOL(init_d2h_sent, AHCIDevice),
1727         VMSTATE_STRUCT_ARRAY(ncq_tfs, AHCIDevice, AHCI_MAX_CMDS,
1728                              1, vmstate_ncq_tfs, NCQTransferState),
1729         VMSTATE_END_OF_LIST()
1730     },
1731 };
1732 
1733 static int ahci_state_post_load(void *opaque, int version_id)
1734 {
1735     int i, j;
1736     struct AHCIDevice *ad;
1737     NCQTransferState *ncq_tfs;
1738     AHCIPortRegs *pr;
1739     AHCIState *s = opaque;
1740 
1741     for (i = 0; i < s->ports; i++) {
1742         ad = &s->dev[i];
1743         pr = &ad->port_regs;
1744 
1745         if (!(pr->cmd & PORT_CMD_START) && (pr->cmd & PORT_CMD_LIST_ON)) {
1746             error_report("AHCI: DMA engine should be off, but status bit "
1747                          "indicates it is still running.");
1748             return -1;
1749         }
1750         if (!(pr->cmd & PORT_CMD_FIS_RX) && (pr->cmd & PORT_CMD_FIS_ON)) {
1751             error_report("AHCI: FIS RX engine should be off, but status bit "
1752                          "indicates it is still running.");
1753             return -1;
1754         }
1755 
1756         /* After a migrate, the DMA/FIS engines are "off" and
1757          * need to be conditionally restarted */
1758         pr->cmd &= ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON);
1759         if (ahci_cond_start_engines(ad) != 0) {
1760             return -1;
1761         }
1762 
1763         for (j = 0; j < AHCI_MAX_CMDS; j++) {
1764             ncq_tfs = &ad->ncq_tfs[j];
1765             ncq_tfs->drive = ad;
1766 
1767             if (ncq_tfs->used != ncq_tfs->halt) {
1768                 return -1;
1769             }
1770             if (!ncq_tfs->halt) {
1771                 continue;
1772             }
1773             if (!is_ncq(ncq_tfs->cmd)) {
1774                 return -1;
1775             }
1776             if (ncq_tfs->slot != ncq_tfs->tag) {
1777                 return -1;
1778             }
1779             /* If ncq_tfs->halt is justly set, the engine should be engaged,
1780              * and the command list buffer should be mapped. */
1781             ncq_tfs->cmdh = get_cmd_header(s, i, ncq_tfs->slot);
1782             if (!ncq_tfs->cmdh) {
1783                 return -1;
1784             }
1785             ahci_populate_sglist(ncq_tfs->drive, &ncq_tfs->sglist,
1786                                  ncq_tfs->cmdh,
1787                                  ncq_tfs->sector_count * BDRV_SECTOR_SIZE,
1788                                  0);
1789             if (ncq_tfs->sector_count != ncq_tfs->sglist.size >> 9) {
1790                 return -1;
1791             }
1792         }
1793 
1794 
1795         /*
1796          * If an error is present, ad->busy_slot will be valid and not -1.
1797          * In this case, an operation is waiting to resume and will re-check
1798          * for additional AHCI commands to execute upon completion.
1799          *
1800          * In the case where no error was present, busy_slot will be -1,
1801          * and we should check to see if there are additional commands waiting.
1802          */
1803         if (ad->busy_slot == -1) {
1804             check_cmd(s, i);
1805         } else {
1806             /* We are in the middle of a command, and may need to access
1807              * the command header in guest memory again. */
1808             if (ad->busy_slot < 0 || ad->busy_slot >= AHCI_MAX_CMDS) {
1809                 return -1;
1810             }
1811             ad->cur_cmd = get_cmd_header(s, i, ad->busy_slot);
1812         }
1813     }
1814 
1815     return 0;
1816 }
1817 
1818 const VMStateDescription vmstate_ahci = {
1819     .name = "ahci",
1820     .version_id = 1,
1821     .post_load = ahci_state_post_load,
1822     .fields = (const VMStateField[]) {
1823         VMSTATE_STRUCT_VARRAY_POINTER_UINT32(dev, AHCIState, ports,
1824                                      vmstate_ahci_device, AHCIDevice),
1825         VMSTATE_UINT32(control_regs.cap, AHCIState),
1826         VMSTATE_UINT32(control_regs.ghc, AHCIState),
1827         VMSTATE_UINT32(control_regs.irqstatus, AHCIState),
1828         VMSTATE_UINT32(control_regs.impl, AHCIState),
1829         VMSTATE_UINT32(control_regs.version, AHCIState),
1830         VMSTATE_UINT32(idp_index, AHCIState),
1831         VMSTATE_UINT32_EQUAL(ports, AHCIState, NULL),
1832         VMSTATE_END_OF_LIST()
1833     },
1834 };
1835 
1836 static const VMStateDescription vmstate_sysbus_ahci = {
1837     .name = "sysbus-ahci",
1838     .fields = (const VMStateField[]) {
1839         VMSTATE_AHCI(ahci, SysbusAHCIState),
1840         VMSTATE_END_OF_LIST()
1841     },
1842 };
1843 
1844 static void sysbus_ahci_reset(DeviceState *dev)
1845 {
1846     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1847 
1848     ahci_reset(&s->ahci);
1849 }
1850 
1851 static void sysbus_ahci_init(Object *obj)
1852 {
1853     SysbusAHCIState *s = SYSBUS_AHCI(obj);
1854     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
1855 
1856     ahci_init(&s->ahci, DEVICE(obj));
1857 
1858     sysbus_init_mmio(sbd, &s->ahci.mem);
1859     sysbus_init_irq(sbd, &s->ahci.irq);
1860 }
1861 
1862 static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
1863 {
1864     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1865 
1866     ahci_realize(&s->ahci, dev, &address_space_memory);
1867 }
1868 
1869 static Property sysbus_ahci_properties[] = {
1870     DEFINE_PROP_UINT32("num-ports", SysbusAHCIState, ahci.ports, 1),
1871     DEFINE_PROP_END_OF_LIST(),
1872 };
1873 
1874 static void sysbus_ahci_class_init(ObjectClass *klass, void *data)
1875 {
1876     DeviceClass *dc = DEVICE_CLASS(klass);
1877 
1878     dc->realize = sysbus_ahci_realize;
1879     dc->vmsd = &vmstate_sysbus_ahci;
1880     device_class_set_props(dc, sysbus_ahci_properties);
1881     dc->reset = sysbus_ahci_reset;
1882     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1883 }
1884 
1885 static const TypeInfo sysbus_ahci_info = {
1886     .name          = TYPE_SYSBUS_AHCI,
1887     .parent        = TYPE_SYS_BUS_DEVICE,
1888     .instance_size = sizeof(SysbusAHCIState),
1889     .instance_init = sysbus_ahci_init,
1890     .class_init    = sysbus_ahci_class_init,
1891 };
1892 
1893 static void sysbus_ahci_register_types(void)
1894 {
1895     type_register_static(&sysbus_ahci_info);
1896 }
1897 
1898 type_init(sysbus_ahci_register_types)
1899 
1900 void ahci_ide_create_devs(AHCIState *ahci, DriveInfo **hd)
1901 {
1902     int i;
1903 
1904     for (i = 0; i < ahci->ports; i++) {
1905         if (hd[i] == NULL) {
1906             continue;
1907         }
1908         ide_bus_create_drive(&ahci->dev[i].port, 0, hd[i]);
1909     }
1910 }
1911