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