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