xref: /openbmc/qemu/hw/ide/ahci.c (revision 922f893e)
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 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 <hw/hw.h>
25 #include <hw/pci/msi.h>
26 #include <hw/i386/pc.h>
27 #include <hw/pci/pci.h>
28 #include <hw/sysbus.h>
29 
30 #include "qemu/error-report.h"
31 #include "sysemu/block-backend.h"
32 #include "sysemu/dma.h"
33 #include "internal.h"
34 #include <hw/ide/pci.h>
35 #include <hw/ide/ahci.h>
36 
37 #define DEBUG_AHCI 0
38 
39 #define DPRINTF(port, fmt, ...) \
40 do { \
41     if (DEBUG_AHCI) { \
42         fprintf(stderr, "ahci: %s: [%d] ", __func__, port); \
43         fprintf(stderr, fmt, ## __VA_ARGS__); \
44     } \
45 } while (0)
46 
47 static void check_cmd(AHCIState *s, int port);
48 static int handle_cmd(AHCIState *s,int port,int slot);
49 static void ahci_reset_port(AHCIState *s, int port);
50 static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis);
51 static void ahci_init_d2h(AHCIDevice *ad);
52 static int ahci_dma_prepare_buf(IDEDMA *dma, int32_t limit);
53 static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes);
54 static bool ahci_map_clb_address(AHCIDevice *ad);
55 static bool ahci_map_fis_address(AHCIDevice *ad);
56 static void ahci_unmap_clb_address(AHCIDevice *ad);
57 static void ahci_unmap_fis_address(AHCIDevice *ad);
58 
59 
60 static uint32_t  ahci_port_read(AHCIState *s, int port, int offset)
61 {
62     uint32_t val;
63     AHCIPortRegs *pr;
64     pr = &s->dev[port].port_regs;
65 
66     switch (offset) {
67     case PORT_LST_ADDR:
68         val = pr->lst_addr;
69         break;
70     case PORT_LST_ADDR_HI:
71         val = pr->lst_addr_hi;
72         break;
73     case PORT_FIS_ADDR:
74         val = pr->fis_addr;
75         break;
76     case PORT_FIS_ADDR_HI:
77         val = pr->fis_addr_hi;
78         break;
79     case PORT_IRQ_STAT:
80         val = pr->irq_stat;
81         break;
82     case PORT_IRQ_MASK:
83         val = pr->irq_mask;
84         break;
85     case PORT_CMD:
86         val = pr->cmd;
87         break;
88     case PORT_TFDATA:
89         val = pr->tfdata;
90         break;
91     case PORT_SIG:
92         val = pr->sig;
93         break;
94     case PORT_SCR_STAT:
95         if (s->dev[port].port.ifs[0].blk) {
96             val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP |
97                   SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE;
98         } else {
99             val = SATA_SCR_SSTATUS_DET_NODEV;
100         }
101         break;
102     case PORT_SCR_CTL:
103         val = pr->scr_ctl;
104         break;
105     case PORT_SCR_ERR:
106         val = pr->scr_err;
107         break;
108     case PORT_SCR_ACT:
109         pr->scr_act &= ~s->dev[port].finished;
110         s->dev[port].finished = 0;
111         val = pr->scr_act;
112         break;
113     case PORT_CMD_ISSUE:
114         val = pr->cmd_issue;
115         break;
116     case PORT_RESERVED:
117     default:
118         val = 0;
119     }
120     DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
121     return val;
122 
123 }
124 
125 static void ahci_irq_raise(AHCIState *s, AHCIDevice *dev)
126 {
127     AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
128     PCIDevice *pci_dev =
129         (PCIDevice *)object_dynamic_cast(OBJECT(d), TYPE_PCI_DEVICE);
130 
131     DPRINTF(0, "raise irq\n");
132 
133     if (pci_dev && msi_enabled(pci_dev)) {
134         msi_notify(pci_dev, 0);
135     } else {
136         qemu_irq_raise(s->irq);
137     }
138 }
139 
140 static void ahci_irq_lower(AHCIState *s, AHCIDevice *dev)
141 {
142     AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
143     PCIDevice *pci_dev =
144         (PCIDevice *)object_dynamic_cast(OBJECT(d), TYPE_PCI_DEVICE);
145 
146     DPRINTF(0, "lower irq\n");
147 
148     if (!pci_dev || !msi_enabled(pci_dev)) {
149         qemu_irq_lower(s->irq);
150     }
151 }
152 
153 static void ahci_check_irq(AHCIState *s)
154 {
155     int i;
156 
157     DPRINTF(-1, "check irq %#x\n", s->control_regs.irqstatus);
158 
159     s->control_regs.irqstatus = 0;
160     for (i = 0; i < s->ports; i++) {
161         AHCIPortRegs *pr = &s->dev[i].port_regs;
162         if (pr->irq_stat & pr->irq_mask) {
163             s->control_regs.irqstatus |= (1 << i);
164         }
165     }
166 
167     if (s->control_regs.irqstatus &&
168         (s->control_regs.ghc & HOST_CTL_IRQ_EN)) {
169             ahci_irq_raise(s, NULL);
170     } else {
171         ahci_irq_lower(s, NULL);
172     }
173 }
174 
175 static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d,
176                              int irq_type)
177 {
178     DPRINTF(d->port_no, "trigger irq %#x -> %x\n",
179             irq_type, d->port_regs.irq_mask & irq_type);
180 
181     d->port_regs.irq_stat |= irq_type;
182     ahci_check_irq(s);
183 }
184 
185 static void map_page(AddressSpace *as, uint8_t **ptr, uint64_t addr,
186                      uint32_t wanted)
187 {
188     hwaddr len = wanted;
189 
190     if (*ptr) {
191         dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
192     }
193 
194     *ptr = dma_memory_map(as, addr, &len, DMA_DIRECTION_FROM_DEVICE);
195     if (len < wanted) {
196         dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len);
197         *ptr = NULL;
198     }
199 }
200 
201 /**
202  * Check the cmd register to see if we should start or stop
203  * the DMA or FIS RX engines.
204  *
205  * @ad: Device to engage.
206  * @allow_stop: Allow device to transition from started to stopped?
207  *   'no' is useful for migration post_load, which does not expect a transition.
208  *
209  * @return 0 on success, -1 on error.
210  */
211 static int ahci_cond_start_engines(AHCIDevice *ad, bool allow_stop)
212 {
213     AHCIPortRegs *pr = &ad->port_regs;
214 
215     if (pr->cmd & PORT_CMD_START) {
216         if (ahci_map_clb_address(ad)) {
217             pr->cmd |= PORT_CMD_LIST_ON;
218         } else {
219             error_report("AHCI: Failed to start DMA engine: "
220                          "bad command list buffer address");
221             return -1;
222         }
223     } else if (pr->cmd & PORT_CMD_LIST_ON) {
224         if (allow_stop) {
225             ahci_unmap_clb_address(ad);
226             pr->cmd = pr->cmd & ~(PORT_CMD_LIST_ON);
227         } else {
228             error_report("AHCI: DMA engine should be off, "
229                          "but appears to still be running");
230             return -1;
231         }
232     }
233 
234     if (pr->cmd & PORT_CMD_FIS_RX) {
235         if (ahci_map_fis_address(ad)) {
236             pr->cmd |= PORT_CMD_FIS_ON;
237         } else {
238             error_report("AHCI: Failed to start FIS receive engine: "
239                          "bad FIS receive buffer address");
240             return -1;
241         }
242     } else if (pr->cmd & PORT_CMD_FIS_ON) {
243         if (allow_stop) {
244             ahci_unmap_fis_address(ad);
245             pr->cmd = pr->cmd & ~(PORT_CMD_FIS_ON);
246         } else {
247             error_report("AHCI: FIS receive engine should be off, "
248                          "but appears to still be running");
249             return -1;
250         }
251     }
252 
253     return 0;
254 }
255 
256 static void  ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)
257 {
258     AHCIPortRegs *pr = &s->dev[port].port_regs;
259 
260     DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
261     switch (offset) {
262         case PORT_LST_ADDR:
263             pr->lst_addr = val;
264             break;
265         case PORT_LST_ADDR_HI:
266             pr->lst_addr_hi = val;
267             break;
268         case PORT_FIS_ADDR:
269             pr->fis_addr = val;
270             break;
271         case PORT_FIS_ADDR_HI:
272             pr->fis_addr_hi = val;
273             break;
274         case PORT_IRQ_STAT:
275             pr->irq_stat &= ~val;
276             ahci_check_irq(s);
277             break;
278         case PORT_IRQ_MASK:
279             pr->irq_mask = val & 0xfdc000ff;
280             ahci_check_irq(s);
281             break;
282         case PORT_CMD:
283             /* Block any Read-only fields from being set;
284              * including LIST_ON and FIS_ON. */
285             pr->cmd = (pr->cmd & PORT_CMD_RO_MASK) | (val & ~PORT_CMD_RO_MASK);
286 
287             /* Check FIS RX and CLB engines, allow transition to false: */
288             ahci_cond_start_engines(&s->dev[port], true);
289 
290             /* XXX usually the FIS would be pending on the bus here and
291                    issuing deferred until the OS enables FIS receival.
292                    Instead, we only submit it once - which works in most
293                    cases, but is a hack. */
294             if ((pr->cmd & PORT_CMD_FIS_ON) &&
295                 !s->dev[port].init_d2h_sent) {
296                 ahci_init_d2h(&s->dev[port]);
297                 s->dev[port].init_d2h_sent = true;
298             }
299 
300             check_cmd(s, port);
301             break;
302         case PORT_TFDATA:
303             /* Read Only. */
304             break;
305         case PORT_SIG:
306             /* Read Only */
307             break;
308         case PORT_SCR_STAT:
309             /* Read Only */
310             break;
311         case PORT_SCR_CTL:
312             if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&
313                 ((val & AHCI_SCR_SCTL_DET) == 0)) {
314                 ahci_reset_port(s, port);
315             }
316             pr->scr_ctl = val;
317             break;
318         case PORT_SCR_ERR:
319             pr->scr_err &= ~val;
320             break;
321         case PORT_SCR_ACT:
322             /* RW1 */
323             pr->scr_act |= val;
324             break;
325         case PORT_CMD_ISSUE:
326             pr->cmd_issue |= val;
327             check_cmd(s, port);
328             break;
329         default:
330             break;
331     }
332 }
333 
334 static uint64_t ahci_mem_read_32(void *opaque, hwaddr addr)
335 {
336     AHCIState *s = opaque;
337     uint32_t val = 0;
338 
339     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
340         switch (addr) {
341         case HOST_CAP:
342             val = s->control_regs.cap;
343             break;
344         case HOST_CTL:
345             val = s->control_regs.ghc;
346             break;
347         case HOST_IRQ_STAT:
348             val = s->control_regs.irqstatus;
349             break;
350         case HOST_PORTS_IMPL:
351             val = s->control_regs.impl;
352             break;
353         case HOST_VERSION:
354             val = s->control_regs.version;
355             break;
356         }
357 
358         DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val);
359     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
360                (addr < (AHCI_PORT_REGS_START_ADDR +
361                 (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
362         val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
363                              addr & AHCI_PORT_ADDR_OFFSET_MASK);
364     }
365 
366     return val;
367 }
368 
369 
370 /**
371  * AHCI 1.3 section 3 ("HBA Memory Registers")
372  * Support unaligned 8/16/32 bit reads, and 64 bit aligned reads.
373  * Caller is responsible for masking unwanted higher order bytes.
374  */
375 static uint64_t ahci_mem_read(void *opaque, hwaddr addr, unsigned size)
376 {
377     hwaddr aligned = addr & ~0x3;
378     int ofst = addr - aligned;
379     uint64_t lo = ahci_mem_read_32(opaque, aligned);
380     uint64_t hi;
381 
382     /* if < 8 byte read does not cross 4 byte boundary */
383     if (ofst + size <= 4) {
384         return lo >> (ofst * 8);
385     }
386     g_assert_cmpint(size, >, 1);
387 
388     /* If the 64bit read is unaligned, we will produce undefined
389      * results. AHCI does not support unaligned 64bit reads. */
390     hi = ahci_mem_read_32(opaque, aligned + 4);
391     return (hi << 32 | lo) >> (ofst * 8);
392 }
393 
394 
395 static void ahci_mem_write(void *opaque, hwaddr addr,
396                            uint64_t val, unsigned size)
397 {
398     AHCIState *s = opaque;
399 
400     /* Only aligned reads are allowed on AHCI */
401     if (addr & 3) {
402         fprintf(stderr, "ahci: Mis-aligned write to addr 0x"
403                 TARGET_FMT_plx "\n", addr);
404         return;
405     }
406 
407     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
408         DPRINTF(-1, "(addr 0x%08X), val 0x%08"PRIX64"\n", (unsigned) addr, val);
409 
410         switch (addr) {
411             case HOST_CAP: /* R/WO, RO */
412                 /* FIXME handle R/WO */
413                 break;
414             case HOST_CTL: /* R/W */
415                 if (val & HOST_CTL_RESET) {
416                     DPRINTF(-1, "HBA Reset\n");
417                     ahci_reset(s);
418                 } else {
419                     s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;
420                     ahci_check_irq(s);
421                 }
422                 break;
423             case HOST_IRQ_STAT: /* R/WC, RO */
424                 s->control_regs.irqstatus &= ~val;
425                 ahci_check_irq(s);
426                 break;
427             case HOST_PORTS_IMPL: /* R/WO, RO */
428                 /* FIXME handle R/WO */
429                 break;
430             case HOST_VERSION: /* RO */
431                 /* FIXME report write? */
432                 break;
433             default:
434                 DPRINTF(-1, "write to unknown register 0x%x\n", (unsigned)addr);
435         }
436     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
437                (addr < (AHCI_PORT_REGS_START_ADDR +
438                 (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {
439         ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
440                         addr & AHCI_PORT_ADDR_OFFSET_MASK, val);
441     }
442 
443 }
444 
445 static const MemoryRegionOps ahci_mem_ops = {
446     .read = ahci_mem_read,
447     .write = ahci_mem_write,
448     .endianness = DEVICE_LITTLE_ENDIAN,
449 };
450 
451 static uint64_t ahci_idp_read(void *opaque, hwaddr addr,
452                               unsigned size)
453 {
454     AHCIState *s = opaque;
455 
456     if (addr == s->idp_offset) {
457         /* index register */
458         return s->idp_index;
459     } else if (addr == s->idp_offset + 4) {
460         /* data register - do memory read at location selected by index */
461         return ahci_mem_read(opaque, s->idp_index, size);
462     } else {
463         return 0;
464     }
465 }
466 
467 static void ahci_idp_write(void *opaque, hwaddr addr,
468                            uint64_t val, unsigned size)
469 {
470     AHCIState *s = opaque;
471 
472     if (addr == s->idp_offset) {
473         /* index register - mask off reserved bits */
474         s->idp_index = (uint32_t)val & ((AHCI_MEM_BAR_SIZE - 1) & ~3);
475     } else if (addr == s->idp_offset + 4) {
476         /* data register - do memory write at location selected by index */
477         ahci_mem_write(opaque, s->idp_index, val, size);
478     }
479 }
480 
481 static const MemoryRegionOps ahci_idp_ops = {
482     .read = ahci_idp_read,
483     .write = ahci_idp_write,
484     .endianness = DEVICE_LITTLE_ENDIAN,
485 };
486 
487 
488 static void ahci_reg_init(AHCIState *s)
489 {
490     int i;
491 
492     s->control_regs.cap = (s->ports - 1) |
493                           (AHCI_NUM_COMMAND_SLOTS << 8) |
494                           (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) |
495                           HOST_CAP_NCQ | HOST_CAP_AHCI;
496 
497     s->control_regs.impl = (1 << s->ports) - 1;
498 
499     s->control_regs.version = AHCI_VERSION_1_0;
500 
501     for (i = 0; i < s->ports; i++) {
502         s->dev[i].port_state = STATE_RUN;
503     }
504 }
505 
506 static void check_cmd(AHCIState *s, int port)
507 {
508     AHCIPortRegs *pr = &s->dev[port].port_regs;
509     int slot;
510 
511     if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) {
512         for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) {
513             if ((pr->cmd_issue & (1U << slot)) &&
514                 !handle_cmd(s, port, slot)) {
515                 pr->cmd_issue &= ~(1U << slot);
516             }
517         }
518     }
519 }
520 
521 static void ahci_check_cmd_bh(void *opaque)
522 {
523     AHCIDevice *ad = opaque;
524 
525     qemu_bh_delete(ad->check_bh);
526     ad->check_bh = NULL;
527 
528     if ((ad->busy_slot != -1) &&
529         !(ad->port.ifs[0].status & (BUSY_STAT|DRQ_STAT))) {
530         /* no longer busy */
531         ad->port_regs.cmd_issue &= ~(1 << ad->busy_slot);
532         ad->busy_slot = -1;
533     }
534 
535     check_cmd(ad->hba, ad->port_no);
536 }
537 
538 static void ahci_init_d2h(AHCIDevice *ad)
539 {
540     uint8_t init_fis[20];
541     IDEState *ide_state = &ad->port.ifs[0];
542 
543     memset(init_fis, 0, sizeof(init_fis));
544 
545     init_fis[4] = 1;
546     init_fis[12] = 1;
547 
548     if (ide_state->drive_kind == IDE_CD) {
549         init_fis[5] = ide_state->lcyl;
550         init_fis[6] = ide_state->hcyl;
551     }
552 
553     ahci_write_fis_d2h(ad, init_fis);
554 }
555 
556 static void ahci_reset_port(AHCIState *s, int port)
557 {
558     AHCIDevice *d = &s->dev[port];
559     AHCIPortRegs *pr = &d->port_regs;
560     IDEState *ide_state = &d->port.ifs[0];
561     int i;
562 
563     DPRINTF(port, "reset port\n");
564 
565     ide_bus_reset(&d->port);
566     ide_state->ncq_queues = AHCI_MAX_CMDS;
567 
568     pr->scr_stat = 0;
569     pr->scr_err = 0;
570     pr->scr_act = 0;
571     pr->tfdata = 0x7F;
572     pr->sig = 0xFFFFFFFF;
573     d->busy_slot = -1;
574     d->init_d2h_sent = false;
575 
576     ide_state = &s->dev[port].port.ifs[0];
577     if (!ide_state->blk) {
578         return;
579     }
580 
581     /* reset ncq queue */
582     for (i = 0; i < AHCI_MAX_CMDS; i++) {
583         NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[i];
584         if (!ncq_tfs->used) {
585             continue;
586         }
587 
588         if (ncq_tfs->aiocb) {
589             blk_aio_cancel(ncq_tfs->aiocb);
590             ncq_tfs->aiocb = NULL;
591         }
592 
593         /* Maybe we just finished the request thanks to blk_aio_cancel() */
594         if (!ncq_tfs->used) {
595             continue;
596         }
597 
598         qemu_sglist_destroy(&ncq_tfs->sglist);
599         ncq_tfs->used = 0;
600     }
601 
602     s->dev[port].port_state = STATE_RUN;
603     if (!ide_state->blk) {
604         pr->sig = 0;
605         ide_state->status = SEEK_STAT | WRERR_STAT;
606     } else if (ide_state->drive_kind == IDE_CD) {
607         pr->sig = SATA_SIGNATURE_CDROM;
608         ide_state->lcyl = 0x14;
609         ide_state->hcyl = 0xeb;
610         DPRINTF(port, "set lcyl = %d\n", ide_state->lcyl);
611         ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT;
612     } else {
613         pr->sig = SATA_SIGNATURE_DISK;
614         ide_state->status = SEEK_STAT | WRERR_STAT;
615     }
616 
617     ide_state->error = 1;
618     ahci_init_d2h(d);
619 }
620 
621 static void debug_print_fis(uint8_t *fis, int cmd_len)
622 {
623 #if DEBUG_AHCI
624     int i;
625 
626     fprintf(stderr, "fis:");
627     for (i = 0; i < cmd_len; i++) {
628         if ((i & 0xf) == 0) {
629             fprintf(stderr, "\n%02x:",i);
630         }
631         fprintf(stderr, "%02x ",fis[i]);
632     }
633     fprintf(stderr, "\n");
634 #endif
635 }
636 
637 static bool ahci_map_fis_address(AHCIDevice *ad)
638 {
639     AHCIPortRegs *pr = &ad->port_regs;
640     map_page(ad->hba->as, &ad->res_fis,
641              ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
642     return ad->res_fis != NULL;
643 }
644 
645 static void ahci_unmap_fis_address(AHCIDevice *ad)
646 {
647     dma_memory_unmap(ad->hba->as, ad->res_fis, 256,
648                      DMA_DIRECTION_FROM_DEVICE, 256);
649     ad->res_fis = NULL;
650 }
651 
652 static bool ahci_map_clb_address(AHCIDevice *ad)
653 {
654     AHCIPortRegs *pr = &ad->port_regs;
655     ad->cur_cmd = NULL;
656     map_page(ad->hba->as, &ad->lst,
657              ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
658     return ad->lst != NULL;
659 }
660 
661 static void ahci_unmap_clb_address(AHCIDevice *ad)
662 {
663     dma_memory_unmap(ad->hba->as, ad->lst, 1024,
664                      DMA_DIRECTION_FROM_DEVICE, 1024);
665     ad->lst = NULL;
666 }
667 
668 static void ahci_write_fis_sdb(AHCIState *s, int port, uint32_t finished)
669 {
670     AHCIDevice *ad = &s->dev[port];
671     AHCIPortRegs *pr = &ad->port_regs;
672     IDEState *ide_state;
673     SDBFIS *sdb_fis;
674 
675     if (!s->dev[port].res_fis ||
676         !(pr->cmd & PORT_CMD_FIS_RX)) {
677         return;
678     }
679 
680     sdb_fis = (SDBFIS *)&ad->res_fis[RES_FIS_SDBFIS];
681     ide_state = &ad->port.ifs[0];
682 
683     sdb_fis->type = SATA_FIS_TYPE_SDB;
684     /* Interrupt pending & Notification bit */
685     sdb_fis->flags = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
686     sdb_fis->status = ide_state->status & 0x77;
687     sdb_fis->error = ide_state->error;
688     /* update SAct field in SDB_FIS */
689     s->dev[port].finished |= finished;
690     sdb_fis->payload = cpu_to_le32(ad->finished);
691 
692     /* Update shadow registers (except BSY 0x80 and DRQ 0x08) */
693     pr->tfdata = (ad->port.ifs[0].error << 8) |
694         (ad->port.ifs[0].status & 0x77) |
695         (pr->tfdata & 0x88);
696 
697     ahci_trigger_irq(s, ad, PORT_IRQ_SDB_FIS);
698 }
699 
700 static void ahci_write_fis_pio(AHCIDevice *ad, uint16_t len)
701 {
702     AHCIPortRegs *pr = &ad->port_regs;
703     uint8_t *pio_fis, *cmd_fis;
704     uint64_t tbl_addr;
705     dma_addr_t cmd_len = 0x80;
706     IDEState *s = &ad->port.ifs[0];
707 
708     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
709         return;
710     }
711 
712     /* map cmd_fis */
713     tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
714     cmd_fis = dma_memory_map(ad->hba->as, tbl_addr, &cmd_len,
715                              DMA_DIRECTION_TO_DEVICE);
716 
717     if (cmd_fis == NULL) {
718         DPRINTF(ad->port_no, "dma_memory_map failed in ahci_write_fis_pio");
719         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR);
720         return;
721     }
722 
723     if (cmd_len != 0x80) {
724         DPRINTF(ad->port_no,
725                 "dma_memory_map mapped too few bytes in ahci_write_fis_pio");
726         dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
727                          DMA_DIRECTION_TO_DEVICE, cmd_len);
728         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR);
729         return;
730     }
731 
732     pio_fis = &ad->res_fis[RES_FIS_PSFIS];
733 
734     pio_fis[0] = SATA_FIS_TYPE_PIO_SETUP;
735     pio_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
736     pio_fis[2] = s->status;
737     pio_fis[3] = s->error;
738 
739     pio_fis[4] = s->sector;
740     pio_fis[5] = s->lcyl;
741     pio_fis[6] = s->hcyl;
742     pio_fis[7] = s->select;
743     pio_fis[8] = s->hob_sector;
744     pio_fis[9] = s->hob_lcyl;
745     pio_fis[10] = s->hob_hcyl;
746     pio_fis[11] = 0;
747     pio_fis[12] = cmd_fis[12];
748     pio_fis[13] = cmd_fis[13];
749     pio_fis[14] = 0;
750     pio_fis[15] = s->status;
751     pio_fis[16] = len & 255;
752     pio_fis[17] = len >> 8;
753     pio_fis[18] = 0;
754     pio_fis[19] = 0;
755 
756     /* Update shadow registers: */
757     pr->tfdata = (ad->port.ifs[0].error << 8) |
758         ad->port.ifs[0].status;
759 
760     if (pio_fis[2] & ERR_STAT) {
761         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
762     }
763 
764     ahci_trigger_irq(ad->hba, ad, PORT_IRQ_PIOS_FIS);
765 
766     dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
767                      DMA_DIRECTION_TO_DEVICE, cmd_len);
768 }
769 
770 static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
771 {
772     AHCIPortRegs *pr = &ad->port_regs;
773     uint8_t *d2h_fis;
774     int i;
775     dma_addr_t cmd_len = 0x80;
776     int cmd_mapped = 0;
777     IDEState *s = &ad->port.ifs[0];
778 
779     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
780         return;
781     }
782 
783     if (!cmd_fis) {
784         /* map cmd_fis */
785         uint64_t tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
786         cmd_fis = dma_memory_map(ad->hba->as, tbl_addr, &cmd_len,
787                                  DMA_DIRECTION_TO_DEVICE);
788         cmd_mapped = 1;
789     }
790 
791     d2h_fis = &ad->res_fis[RES_FIS_RFIS];
792 
793     d2h_fis[0] = SATA_FIS_TYPE_REGISTER_D2H;
794     d2h_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
795     d2h_fis[2] = s->status;
796     d2h_fis[3] = s->error;
797 
798     d2h_fis[4] = s->sector;
799     d2h_fis[5] = s->lcyl;
800     d2h_fis[6] = s->hcyl;
801     d2h_fis[7] = s->select;
802     d2h_fis[8] = s->hob_sector;
803     d2h_fis[9] = s->hob_lcyl;
804     d2h_fis[10] = s->hob_hcyl;
805     d2h_fis[11] = 0;
806     d2h_fis[12] = cmd_fis[12];
807     d2h_fis[13] = cmd_fis[13];
808     for (i = 14; i < 20; i++) {
809         d2h_fis[i] = 0;
810     }
811 
812     /* Update shadow registers: */
813     pr->tfdata = (ad->port.ifs[0].error << 8) |
814         ad->port.ifs[0].status;
815 
816     if (d2h_fis[2] & ERR_STAT) {
817         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR);
818     }
819 
820     ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS);
821 
822     if (cmd_mapped) {
823         dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len,
824                          DMA_DIRECTION_TO_DEVICE, cmd_len);
825     }
826 }
827 
828 static int prdt_tbl_entry_size(const AHCI_SG *tbl)
829 {
830     /* flags_size is zero-based */
831     return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1;
832 }
833 
834 static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist,
835                                 int64_t limit, int32_t offset)
836 {
837     AHCICmdHdr *cmd = ad->cur_cmd;
838     uint16_t opts = le16_to_cpu(cmd->opts);
839     uint16_t prdtl = le16_to_cpu(cmd->prdtl);
840     uint64_t cfis_addr = le64_to_cpu(cmd->tbl_addr);
841     uint64_t prdt_addr = cfis_addr + 0x80;
842     dma_addr_t prdt_len = (prdtl * sizeof(AHCI_SG));
843     dma_addr_t real_prdt_len = prdt_len;
844     uint8_t *prdt;
845     int i;
846     int r = 0;
847     uint64_t sum = 0;
848     int off_idx = -1;
849     int64_t off_pos = -1;
850     int tbl_entry_size;
851     IDEBus *bus = &ad->port;
852     BusState *qbus = BUS(bus);
853 
854     /*
855      * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support
856      * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a
857      * 512 byte sector size. We limit the PRDT in this implementation to
858      * a reasonably large 2GiB, which can accommodate the maximum transfer
859      * request for sector sizes up to 32K.
860      */
861 
862     if (!prdtl) {
863         DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);
864         return -1;
865     }
866 
867     /* map PRDT */
868     if (!(prdt = dma_memory_map(ad->hba->as, prdt_addr, &prdt_len,
869                                 DMA_DIRECTION_TO_DEVICE))){
870         DPRINTF(ad->port_no, "map failed\n");
871         return -1;
872     }
873 
874     if (prdt_len < real_prdt_len) {
875         DPRINTF(ad->port_no, "mapped less than expected\n");
876         r = -1;
877         goto out;
878     }
879 
880     /* Get entries in the PRDT, init a qemu sglist accordingly */
881     if (prdtl > 0) {
882         AHCI_SG *tbl = (AHCI_SG *)prdt;
883         sum = 0;
884         for (i = 0; i < prdtl; i++) {
885             tbl_entry_size = prdt_tbl_entry_size(&tbl[i]);
886             if (offset < (sum + tbl_entry_size)) {
887                 off_idx = i;
888                 off_pos = offset - sum;
889                 break;
890             }
891             sum += tbl_entry_size;
892         }
893         if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {
894             DPRINTF(ad->port_no, "%s: Incorrect offset! "
895                             "off_idx: %d, off_pos: %"PRId64"\n",
896                             __func__, off_idx, off_pos);
897             r = -1;
898             goto out;
899         }
900 
901         qemu_sglist_init(sglist, qbus->parent, (prdtl - off_idx),
902                          ad->hba->as);
903         qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr) + off_pos,
904                         MIN(prdt_tbl_entry_size(&tbl[off_idx]) - off_pos,
905                             limit));
906 
907         for (i = off_idx + 1; i < prdtl && sglist->size < limit; i++) {
908             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
909                             MIN(prdt_tbl_entry_size(&tbl[i]),
910                                 limit - sglist->size));
911             if (sglist->size > INT32_MAX) {
912                 error_report("AHCI Physical Region Descriptor Table describes "
913                              "more than 2 GiB.\n");
914                 qemu_sglist_destroy(sglist);
915                 r = -1;
916                 goto out;
917             }
918         }
919     }
920 
921 out:
922     dma_memory_unmap(ad->hba->as, prdt, prdt_len,
923                      DMA_DIRECTION_TO_DEVICE, prdt_len);
924     return r;
925 }
926 
927 static void ncq_err(NCQTransferState *ncq_tfs)
928 {
929     IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
930 
931     ide_state->error = ABRT_ERR;
932     ide_state->status = READY_STAT | ERR_STAT;
933     ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
934 }
935 
936 static void ncq_cb(void *opaque, int ret)
937 {
938     NCQTransferState *ncq_tfs = (NCQTransferState *)opaque;
939     IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
940 
941     if (ret == -ECANCELED) {
942         return;
943     }
944     /* Clear bit for this tag in SActive */
945     ncq_tfs->drive->port_regs.scr_act &= ~(1 << ncq_tfs->tag);
946 
947     if (ret < 0) {
948         ncq_err(ncq_tfs);
949     } else {
950         ide_state->status = READY_STAT | SEEK_STAT;
951     }
952 
953     ahci_write_fis_sdb(ncq_tfs->drive->hba, ncq_tfs->drive->port_no,
954                        (1 << ncq_tfs->tag));
955 
956     DPRINTF(ncq_tfs->drive->port_no, "NCQ transfer tag %d finished\n",
957             ncq_tfs->tag);
958 
959     block_acct_done(blk_get_stats(ncq_tfs->drive->port.ifs[0].blk),
960                     &ncq_tfs->acct);
961     qemu_sglist_destroy(&ncq_tfs->sglist);
962     ncq_tfs->used = 0;
963 }
964 
965 static int is_ncq(uint8_t ata_cmd)
966 {
967     /* Based on SATA 3.2 section 13.6.3.2 */
968     switch (ata_cmd) {
969     case READ_FPDMA_QUEUED:
970     case WRITE_FPDMA_QUEUED:
971     case NCQ_NON_DATA:
972     case RECEIVE_FPDMA_QUEUED:
973     case SEND_FPDMA_QUEUED:
974         return 1;
975     default:
976         return 0;
977     }
978 }
979 
980 static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
981                                 int slot)
982 {
983     AHCIDevice *ad = &s->dev[port];
984     IDEState *ide_state = &ad->port.ifs[0];
985     NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;
986     uint8_t tag = ncq_fis->tag >> 3;
987     NCQTransferState *ncq_tfs = &ad->ncq_tfs[tag];
988     size_t size;
989 
990     g_assert(is_ncq(ncq_fis->command));
991     if (ncq_tfs->used) {
992         /* error - already in use */
993         fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);
994         return;
995     }
996 
997     ncq_tfs->used = 1;
998     ncq_tfs->drive = ad;
999     ncq_tfs->slot = slot;
1000     ncq_tfs->cmd = ncq_fis->command;
1001     ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
1002                    ((uint64_t)ncq_fis->lba4 << 32) |
1003                    ((uint64_t)ncq_fis->lba3 << 24) |
1004                    ((uint64_t)ncq_fis->lba2 << 16) |
1005                    ((uint64_t)ncq_fis->lba1 << 8) |
1006                    (uint64_t)ncq_fis->lba0;
1007     ncq_tfs->tag = tag;
1008 
1009     /* Sanity-check the NCQ packet */
1010     if (tag != slot) {
1011         DPRINTF(port, "Warn: NCQ slot (%d) did not match the given tag (%d)\n",
1012                 slot, tag);
1013     }
1014 
1015     if (ncq_fis->aux0 || ncq_fis->aux1 || ncq_fis->aux2 || ncq_fis->aux3) {
1016         DPRINTF(port, "Warn: Attempt to use NCQ auxiliary fields.\n");
1017     }
1018     if (ncq_fis->prio || ncq_fis->icc) {
1019         DPRINTF(port, "Warn: Unsupported attempt to use PRIO/ICC fields\n");
1020     }
1021     if (ncq_fis->fua & NCQ_FIS_FUA_MASK) {
1022         DPRINTF(port, "Warn: Unsupported attempt to use Force Unit Access\n");
1023     }
1024     if (ncq_fis->tag & NCQ_FIS_RARC_MASK) {
1025         DPRINTF(port, "Warn: Unsupported attempt to use Rebuild Assist\n");
1026     }
1027 
1028     ncq_tfs->sector_count = ((uint16_t)ncq_fis->sector_count_high << 8) |
1029                                 ncq_fis->sector_count_low;
1030     size = ncq_tfs->sector_count * 512;
1031     ahci_populate_sglist(ad, &ncq_tfs->sglist, size, 0);
1032 
1033     if (ncq_tfs->sglist.size < size) {
1034         error_report("ahci: PRDT length for NCQ command (0x%zx) "
1035                      "is smaller than the requested size (0x%zx)",
1036                      ncq_tfs->sglist.size, size);
1037         qemu_sglist_destroy(&ncq_tfs->sglist);
1038         ncq_err(ncq_tfs);
1039         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_OVERFLOW);
1040         return;
1041     } else if (ncq_tfs->sglist.size != size) {
1042         DPRINTF(port, "Warn: PRDTL (0x%zx)"
1043                 " does not match requested size (0x%zx)",
1044                 ncq_tfs->sglist.size, size);
1045     }
1046 
1047     DPRINTF(port, "NCQ transfer LBA from %"PRId64" to %"PRId64", "
1048             "drive max %"PRId64"\n",
1049             ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 1,
1050             ide_state->nb_sectors - 1);
1051 
1052     switch (ncq_tfs->cmd) {
1053     case READ_FPDMA_QUEUED:
1054         DPRINTF(port, "NCQ reading %d sectors from LBA %"PRId64", tag %d\n",
1055                 ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
1056 
1057         DPRINTF(port, "tag %d aio read %"PRId64"\n",
1058                 ncq_tfs->tag, ncq_tfs->lba);
1059 
1060         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1061                        &ncq_tfs->sglist, BLOCK_ACCT_READ);
1062         ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
1063                                       ncq_tfs->lba, ncq_cb, ncq_tfs);
1064         break;
1065     case WRITE_FPDMA_QUEUED:
1066         DPRINTF(port, "NCQ writing %d sectors to LBA %"PRId64", tag %d\n",
1067                 ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
1068 
1069         DPRINTF(port, "tag %d aio write %"PRId64"\n",
1070                 ncq_tfs->tag, ncq_tfs->lba);
1071 
1072         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1073                        &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
1074         ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
1075                                        ncq_tfs->lba, ncq_cb, ncq_tfs);
1076         break;
1077     default:
1078         DPRINTF(port, "error: unsupported NCQ command (0x%02x) received\n",
1079                 ncq_tfs->cmd);
1080         qemu_sglist_destroy(&ncq_tfs->sglist);
1081         ncq_err(ncq_tfs);
1082     }
1083 }
1084 
1085 static void handle_reg_h2d_fis(AHCIState *s, int port,
1086                                int slot, uint8_t *cmd_fis)
1087 {
1088     IDEState *ide_state = &s->dev[port].port.ifs[0];
1089     AHCICmdHdr *cmd = s->dev[port].cur_cmd;
1090     uint16_t opts = le16_to_cpu(cmd->opts);
1091 
1092     if (cmd_fis[1] & 0x0F) {
1093         DPRINTF(port, "Port Multiplier not supported."
1094                 " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1095                 cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1096         return;
1097     }
1098 
1099     if (cmd_fis[1] & 0x70) {
1100         DPRINTF(port, "Reserved flags set in H2D Register FIS."
1101                 " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1102                 cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1103         return;
1104     }
1105 
1106     if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {
1107         switch (s->dev[port].port_state) {
1108         case STATE_RUN:
1109             if (cmd_fis[15] & ATA_SRST) {
1110                 s->dev[port].port_state = STATE_RESET;
1111             }
1112             break;
1113         case STATE_RESET:
1114             if (!(cmd_fis[15] & ATA_SRST)) {
1115                 ahci_reset_port(s, port);
1116             }
1117             break;
1118         }
1119         return;
1120     }
1121 
1122     /* Check for NCQ command */
1123     if (is_ncq(cmd_fis[2])) {
1124         process_ncq_command(s, port, cmd_fis, slot);
1125         return;
1126     }
1127 
1128     /* Decompose the FIS:
1129      * AHCI does not interpret FIS packets, it only forwards them.
1130      * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.
1131      * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.
1132      *
1133      * ATA4 describes sector number for LBA28/CHS commands.
1134      * ATA6 describes sector number for LBA48 commands.
1135      * ATA8 deprecates CHS fully, describing only LBA28/48.
1136      *
1137      * We dutifully convert the FIS into IDE registers, and allow the
1138      * core layer to interpret them as needed. */
1139     ide_state->feature = cmd_fis[3];
1140     ide_state->sector = cmd_fis[4];      /* LBA 7:0 */
1141     ide_state->lcyl = cmd_fis[5];        /* LBA 15:8  */
1142     ide_state->hcyl = cmd_fis[6];        /* LBA 23:16 */
1143     ide_state->select = cmd_fis[7];      /* LBA 27:24 (LBA28) */
1144     ide_state->hob_sector = cmd_fis[8];  /* LBA 31:24 */
1145     ide_state->hob_lcyl = cmd_fis[9];    /* LBA 39:32 */
1146     ide_state->hob_hcyl = cmd_fis[10];   /* LBA 47:40 */
1147     ide_state->hob_feature = cmd_fis[11];
1148     ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
1149     /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */
1150     /* 15: Only valid when UPDATE_COMMAND not set. */
1151 
1152     /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
1153      * table to ide_state->io_buffer */
1154     if (opts & AHCI_CMD_ATAPI) {
1155         memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
1156         debug_print_fis(ide_state->io_buffer, 0x10);
1157         s->dev[port].done_atapi_packet = false;
1158         /* XXX send PIO setup FIS */
1159     }
1160 
1161     ide_state->error = 0;
1162 
1163     /* Reset transferred byte counter */
1164     cmd->status = 0;
1165 
1166     /* We're ready to process the command in FIS byte 2. */
1167     ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);
1168 }
1169 
1170 static int handle_cmd(AHCIState *s, int port, int slot)
1171 {
1172     IDEState *ide_state;
1173     uint64_t tbl_addr;
1174     AHCICmdHdr *cmd;
1175     uint8_t *cmd_fis;
1176     dma_addr_t cmd_len;
1177 
1178     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1179         /* Engine currently busy, try again later */
1180         DPRINTF(port, "engine busy\n");
1181         return -1;
1182     }
1183 
1184     if (!s->dev[port].lst) {
1185         DPRINTF(port, "error: lst not given but cmd handled");
1186         return -1;
1187     }
1188     cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];
1189     /* remember current slot handle for later */
1190     s->dev[port].cur_cmd = cmd;
1191 
1192     /* The device we are working for */
1193     ide_state = &s->dev[port].port.ifs[0];
1194     if (!ide_state->blk) {
1195         DPRINTF(port, "error: guest accessed unused port");
1196         return -1;
1197     }
1198 
1199     tbl_addr = le64_to_cpu(cmd->tbl_addr);
1200     cmd_len = 0x80;
1201     cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,
1202                              DMA_DIRECTION_FROM_DEVICE);
1203     if (!cmd_fis) {
1204         DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
1205         return -1;
1206     } else if (cmd_len != 0x80) {
1207         ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR);
1208         DPRINTF(port, "error: dma_memory_map failed: "
1209                 "(len(%02"PRIx64") != 0x80)\n",
1210                 cmd_len);
1211         goto out;
1212     }
1213     debug_print_fis(cmd_fis, 0x80);
1214 
1215     switch (cmd_fis[0]) {
1216         case SATA_FIS_TYPE_REGISTER_H2D:
1217             handle_reg_h2d_fis(s, port, slot, cmd_fis);
1218             break;
1219         default:
1220             DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
1221                           "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
1222                           cmd_fis[2]);
1223             break;
1224     }
1225 
1226 out:
1227     dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,
1228                      cmd_len);
1229 
1230     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1231         /* async command, complete later */
1232         s->dev[port].busy_slot = slot;
1233         return -1;
1234     }
1235 
1236     /* done handling the command */
1237     return 0;
1238 }
1239 
1240 /* DMA dev <-> ram */
1241 static void ahci_start_transfer(IDEDMA *dma)
1242 {
1243     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1244     IDEState *s = &ad->port.ifs[0];
1245     uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
1246     /* write == ram -> device */
1247     uint16_t opts = le16_to_cpu(ad->cur_cmd->opts);
1248     int is_write = opts & AHCI_CMD_WRITE;
1249     int is_atapi = opts & AHCI_CMD_ATAPI;
1250     int has_sglist = 0;
1251 
1252     if (is_atapi && !ad->done_atapi_packet) {
1253         /* already prepopulated iobuffer */
1254         ad->done_atapi_packet = true;
1255         size = 0;
1256         goto out;
1257     }
1258 
1259     if (ahci_dma_prepare_buf(dma, size)) {
1260         has_sglist = 1;
1261     }
1262 
1263     DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",
1264             is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",
1265             has_sglist ? "" : "o");
1266 
1267     if (has_sglist && size) {
1268         if (is_write) {
1269             dma_buf_write(s->data_ptr, size, &s->sg);
1270         } else {
1271             dma_buf_read(s->data_ptr, size, &s->sg);
1272         }
1273     }
1274 
1275 out:
1276     /* declare that we processed everything */
1277     s->data_ptr = s->data_end;
1278 
1279     /* Update number of transferred bytes, destroy sglist */
1280     ahci_commit_buf(dma, size);
1281 
1282     s->end_transfer_func(s);
1283 
1284     if (!(s->status & DRQ_STAT)) {
1285         /* done with PIO send/receive */
1286         ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));
1287     }
1288 }
1289 
1290 static void ahci_start_dma(IDEDMA *dma, IDEState *s,
1291                            BlockCompletionFunc *dma_cb)
1292 {
1293     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1294     DPRINTF(ad->port_no, "\n");
1295     s->io_buffer_offset = 0;
1296     dma_cb(s, 0);
1297 }
1298 
1299 static void ahci_restart_dma(IDEDMA *dma)
1300 {
1301     /* Nothing to do, ahci_start_dma already resets s->io_buffer_offset.  */
1302 }
1303 
1304 /**
1305  * Called in DMA R/W chains to read the PRDT, utilizing ahci_populate_sglist.
1306  * Not currently invoked by PIO R/W chains,
1307  * which invoke ahci_populate_sglist via ahci_start_transfer.
1308  */
1309 static int32_t ahci_dma_prepare_buf(IDEDMA *dma, int32_t limit)
1310 {
1311     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1312     IDEState *s = &ad->port.ifs[0];
1313 
1314     if (ahci_populate_sglist(ad, &s->sg, limit, s->io_buffer_offset) == -1) {
1315         DPRINTF(ad->port_no, "ahci_dma_prepare_buf failed.\n");
1316         return -1;
1317     }
1318     s->io_buffer_size = s->sg.size;
1319 
1320     DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
1321     return s->io_buffer_size;
1322 }
1323 
1324 /**
1325  * Destroys the scatter-gather list,
1326  * and updates the command header with a bytes-read value.
1327  * called explicitly via ahci_dma_rw_buf (ATAPI DMA),
1328  * and ahci_start_transfer (PIO R/W),
1329  * and called via callback from ide_dma_cb for DMA R/W paths.
1330  */
1331 static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes)
1332 {
1333     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1334     IDEState *s = &ad->port.ifs[0];
1335 
1336     tx_bytes += le32_to_cpu(ad->cur_cmd->status);
1337     ad->cur_cmd->status = cpu_to_le32(tx_bytes);
1338 
1339     qemu_sglist_destroy(&s->sg);
1340 }
1341 
1342 static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
1343 {
1344     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1345     IDEState *s = &ad->port.ifs[0];
1346     uint8_t *p = s->io_buffer + s->io_buffer_index;
1347     int l = s->io_buffer_size - s->io_buffer_index;
1348 
1349     if (ahci_populate_sglist(ad, &s->sg, l, s->io_buffer_offset)) {
1350         return 0;
1351     }
1352 
1353     if (is_write) {
1354         dma_buf_read(p, l, &s->sg);
1355     } else {
1356         dma_buf_write(p, l, &s->sg);
1357     }
1358 
1359     /* free sglist, update byte count */
1360     ahci_commit_buf(dma, l);
1361 
1362     s->io_buffer_index += l;
1363     s->io_buffer_offset += l;
1364 
1365     DPRINTF(ad->port_no, "len=%#x\n", l);
1366 
1367     return 1;
1368 }
1369 
1370 static void ahci_cmd_done(IDEDMA *dma)
1371 {
1372     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1373 
1374     DPRINTF(ad->port_no, "cmd done\n");
1375 
1376     /* update d2h status */
1377     ahci_write_fis_d2h(ad, NULL);
1378 
1379     if (!ad->check_bh) {
1380         /* maybe we still have something to process, check later */
1381         ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad);
1382         qemu_bh_schedule(ad->check_bh);
1383     }
1384 }
1385 
1386 static void ahci_irq_set(void *opaque, int n, int level)
1387 {
1388 }
1389 
1390 static const IDEDMAOps ahci_dma_ops = {
1391     .start_dma = ahci_start_dma,
1392     .restart_dma = ahci_restart_dma,
1393     .start_transfer = ahci_start_transfer,
1394     .prepare_buf = ahci_dma_prepare_buf,
1395     .commit_buf = ahci_commit_buf,
1396     .rw_buf = ahci_dma_rw_buf,
1397     .cmd_done = ahci_cmd_done,
1398 };
1399 
1400 void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports)
1401 {
1402     qemu_irq *irqs;
1403     int i;
1404 
1405     s->as = as;
1406     s->ports = ports;
1407     s->dev = g_new0(AHCIDevice, ports);
1408     ahci_reg_init(s);
1409     /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1410     memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s,
1411                           "ahci", AHCI_MEM_BAR_SIZE);
1412     memory_region_init_io(&s->idp, OBJECT(qdev), &ahci_idp_ops, s,
1413                           "ahci-idp", 32);
1414 
1415     irqs = qemu_allocate_irqs(ahci_irq_set, s, s->ports);
1416 
1417     for (i = 0; i < s->ports; i++) {
1418         AHCIDevice *ad = &s->dev[i];
1419 
1420         ide_bus_new(&ad->port, sizeof(ad->port), qdev, i, 1);
1421         ide_init2(&ad->port, irqs[i]);
1422 
1423         ad->hba = s;
1424         ad->port_no = i;
1425         ad->port.dma = &ad->dma;
1426         ad->port.dma->ops = &ahci_dma_ops;
1427         ide_register_restart_cb(&ad->port);
1428     }
1429 }
1430 
1431 void ahci_uninit(AHCIState *s)
1432 {
1433     g_free(s->dev);
1434 }
1435 
1436 void ahci_reset(AHCIState *s)
1437 {
1438     AHCIPortRegs *pr;
1439     int i;
1440 
1441     s->control_regs.irqstatus = 0;
1442     /* AHCI Enable (AE)
1443      * The implementation of this bit is dependent upon the value of the
1444      * CAP.SAM bit. If CAP.SAM is '0', then GHC.AE shall be read-write and
1445      * shall have a reset value of '0'. If CAP.SAM is '1', then AE shall be
1446      * read-only and shall have a reset value of '1'.
1447      *
1448      * We set HOST_CAP_AHCI so we must enable AHCI at reset.
1449      */
1450     s->control_regs.ghc = HOST_CTL_AHCI_EN;
1451 
1452     for (i = 0; i < s->ports; i++) {
1453         pr = &s->dev[i].port_regs;
1454         pr->irq_stat = 0;
1455         pr->irq_mask = 0;
1456         pr->scr_ctl = 0;
1457         pr->cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
1458         ahci_reset_port(s, i);
1459     }
1460 }
1461 
1462 static const VMStateDescription vmstate_ahci_device = {
1463     .name = "ahci port",
1464     .version_id = 1,
1465     .fields = (VMStateField[]) {
1466         VMSTATE_IDE_BUS(port, AHCIDevice),
1467         VMSTATE_IDE_DRIVE(port.ifs[0], AHCIDevice),
1468         VMSTATE_UINT32(port_state, AHCIDevice),
1469         VMSTATE_UINT32(finished, AHCIDevice),
1470         VMSTATE_UINT32(port_regs.lst_addr, AHCIDevice),
1471         VMSTATE_UINT32(port_regs.lst_addr_hi, AHCIDevice),
1472         VMSTATE_UINT32(port_regs.fis_addr, AHCIDevice),
1473         VMSTATE_UINT32(port_regs.fis_addr_hi, AHCIDevice),
1474         VMSTATE_UINT32(port_regs.irq_stat, AHCIDevice),
1475         VMSTATE_UINT32(port_regs.irq_mask, AHCIDevice),
1476         VMSTATE_UINT32(port_regs.cmd, AHCIDevice),
1477         VMSTATE_UINT32(port_regs.tfdata, AHCIDevice),
1478         VMSTATE_UINT32(port_regs.sig, AHCIDevice),
1479         VMSTATE_UINT32(port_regs.scr_stat, AHCIDevice),
1480         VMSTATE_UINT32(port_regs.scr_ctl, AHCIDevice),
1481         VMSTATE_UINT32(port_regs.scr_err, AHCIDevice),
1482         VMSTATE_UINT32(port_regs.scr_act, AHCIDevice),
1483         VMSTATE_UINT32(port_regs.cmd_issue, AHCIDevice),
1484         VMSTATE_BOOL(done_atapi_packet, AHCIDevice),
1485         VMSTATE_INT32(busy_slot, AHCIDevice),
1486         VMSTATE_BOOL(init_d2h_sent, AHCIDevice),
1487         VMSTATE_END_OF_LIST()
1488     },
1489 };
1490 
1491 static int ahci_state_post_load(void *opaque, int version_id)
1492 {
1493     int i;
1494     struct AHCIDevice *ad;
1495     AHCIState *s = opaque;
1496 
1497     for (i = 0; i < s->ports; i++) {
1498         ad = &s->dev[i];
1499 
1500         /* Only remap the CLB address if appropriate, disallowing a state
1501          * transition from 'on' to 'off' it should be consistent here. */
1502         if (ahci_cond_start_engines(ad, false) != 0) {
1503             return -1;
1504         }
1505 
1506         /*
1507          * If an error is present, ad->busy_slot will be valid and not -1.
1508          * In this case, an operation is waiting to resume and will re-check
1509          * for additional AHCI commands to execute upon completion.
1510          *
1511          * In the case where no error was present, busy_slot will be -1,
1512          * and we should check to see if there are additional commands waiting.
1513          */
1514         if (ad->busy_slot == -1) {
1515             check_cmd(s, i);
1516         } else {
1517             /* We are in the middle of a command, and may need to access
1518              * the command header in guest memory again. */
1519             if (ad->busy_slot < 0 || ad->busy_slot >= AHCI_MAX_CMDS) {
1520                 return -1;
1521             }
1522             ad->cur_cmd = &((AHCICmdHdr *)ad->lst)[ad->busy_slot];
1523         }
1524     }
1525 
1526     return 0;
1527 }
1528 
1529 const VMStateDescription vmstate_ahci = {
1530     .name = "ahci",
1531     .version_id = 1,
1532     .post_load = ahci_state_post_load,
1533     .fields = (VMStateField[]) {
1534         VMSTATE_STRUCT_VARRAY_POINTER_INT32(dev, AHCIState, ports,
1535                                      vmstate_ahci_device, AHCIDevice),
1536         VMSTATE_UINT32(control_regs.cap, AHCIState),
1537         VMSTATE_UINT32(control_regs.ghc, AHCIState),
1538         VMSTATE_UINT32(control_regs.irqstatus, AHCIState),
1539         VMSTATE_UINT32(control_regs.impl, AHCIState),
1540         VMSTATE_UINT32(control_regs.version, AHCIState),
1541         VMSTATE_UINT32(idp_index, AHCIState),
1542         VMSTATE_INT32_EQUAL(ports, AHCIState),
1543         VMSTATE_END_OF_LIST()
1544     },
1545 };
1546 
1547 #define TYPE_SYSBUS_AHCI "sysbus-ahci"
1548 #define SYSBUS_AHCI(obj) OBJECT_CHECK(SysbusAHCIState, (obj), TYPE_SYSBUS_AHCI)
1549 
1550 typedef struct SysbusAHCIState {
1551     /*< private >*/
1552     SysBusDevice parent_obj;
1553     /*< public >*/
1554 
1555     AHCIState ahci;
1556     uint32_t num_ports;
1557 } SysbusAHCIState;
1558 
1559 static const VMStateDescription vmstate_sysbus_ahci = {
1560     .name = "sysbus-ahci",
1561     .fields = (VMStateField[]) {
1562         VMSTATE_AHCI(ahci, SysbusAHCIState),
1563         VMSTATE_END_OF_LIST()
1564     },
1565 };
1566 
1567 static void sysbus_ahci_reset(DeviceState *dev)
1568 {
1569     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1570 
1571     ahci_reset(&s->ahci);
1572 }
1573 
1574 static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
1575 {
1576     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1577     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1578 
1579     ahci_init(&s->ahci, dev, &address_space_memory, s->num_ports);
1580 
1581     sysbus_init_mmio(sbd, &s->ahci.mem);
1582     sysbus_init_irq(sbd, &s->ahci.irq);
1583 }
1584 
1585 static Property sysbus_ahci_properties[] = {
1586     DEFINE_PROP_UINT32("num-ports", SysbusAHCIState, num_ports, 1),
1587     DEFINE_PROP_END_OF_LIST(),
1588 };
1589 
1590 static void sysbus_ahci_class_init(ObjectClass *klass, void *data)
1591 {
1592     DeviceClass *dc = DEVICE_CLASS(klass);
1593 
1594     dc->realize = sysbus_ahci_realize;
1595     dc->vmsd = &vmstate_sysbus_ahci;
1596     dc->props = sysbus_ahci_properties;
1597     dc->reset = sysbus_ahci_reset;
1598     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1599 }
1600 
1601 static const TypeInfo sysbus_ahci_info = {
1602     .name          = TYPE_SYSBUS_AHCI,
1603     .parent        = TYPE_SYS_BUS_DEVICE,
1604     .instance_size = sizeof(SysbusAHCIState),
1605     .class_init    = sysbus_ahci_class_init,
1606 };
1607 
1608 static void sysbus_ahci_register_types(void)
1609 {
1610     type_register_static(&sysbus_ahci_info);
1611 }
1612 
1613 type_init(sysbus_ahci_register_types)
1614 
1615 void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd)
1616 {
1617     AHCIPCIState *d = ICH_AHCI(dev);
1618     AHCIState *ahci = &d->ahci;
1619     int i;
1620 
1621     for (i = 0; i < ahci->ports; i++) {
1622         if (hd[i] == NULL) {
1623             continue;
1624         }
1625         ide_create_drive(&ahci->dev[i].port, 0, hd[i]);
1626     }
1627 
1628 }
1629