xref: /openbmc/qemu/hw/ide/ahci.c (revision 631ddc22)
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 execute_ncq_command(NCQTransferState *ncq_tfs)
981 {
982     AHCIDevice *ad = ncq_tfs->drive;
983     IDEState *ide_state = &ad->port.ifs[0];
984     int port = ad->port_no;
985     g_assert(is_ncq(ncq_tfs->cmd));
986 
987     switch (ncq_tfs->cmd) {
988     case READ_FPDMA_QUEUED:
989         DPRINTF(port, "NCQ reading %d sectors from LBA %"PRId64", tag %d\n",
990                 ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
991 
992         DPRINTF(port, "tag %d aio read %"PRId64"\n",
993                 ncq_tfs->tag, ncq_tfs->lba);
994 
995         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
996                        &ncq_tfs->sglist, BLOCK_ACCT_READ);
997         ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
998                                       ncq_tfs->lba, ncq_cb, ncq_tfs);
999         break;
1000     case WRITE_FPDMA_QUEUED:
1001         DPRINTF(port, "NCQ writing %d sectors to LBA %"PRId64", tag %d\n",
1002                 ncq_tfs->sector_count, ncq_tfs->lba, ncq_tfs->tag);
1003 
1004         DPRINTF(port, "tag %d aio write %"PRId64"\n",
1005                 ncq_tfs->tag, ncq_tfs->lba);
1006 
1007         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
1008                        &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
1009         ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
1010                                        ncq_tfs->lba, ncq_cb, ncq_tfs);
1011         break;
1012     default:
1013         DPRINTF(port, "error: unsupported NCQ command (0x%02x) received\n",
1014                 ncq_tfs->cmd);
1015         qemu_sglist_destroy(&ncq_tfs->sglist);
1016         ncq_err(ncq_tfs);
1017     }
1018 }
1019 
1020 
1021 static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
1022                                 int slot)
1023 {
1024     AHCIDevice *ad = &s->dev[port];
1025     IDEState *ide_state = &ad->port.ifs[0];
1026     NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;
1027     uint8_t tag = ncq_fis->tag >> 3;
1028     NCQTransferState *ncq_tfs = &ad->ncq_tfs[tag];
1029     size_t size;
1030 
1031     g_assert(is_ncq(ncq_fis->command));
1032     if (ncq_tfs->used) {
1033         /* error - already in use */
1034         fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);
1035         return;
1036     }
1037 
1038     ncq_tfs->used = 1;
1039     ncq_tfs->drive = ad;
1040     ncq_tfs->slot = slot;
1041     ncq_tfs->cmd = ncq_fis->command;
1042     ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
1043                    ((uint64_t)ncq_fis->lba4 << 32) |
1044                    ((uint64_t)ncq_fis->lba3 << 24) |
1045                    ((uint64_t)ncq_fis->lba2 << 16) |
1046                    ((uint64_t)ncq_fis->lba1 << 8) |
1047                    (uint64_t)ncq_fis->lba0;
1048     ncq_tfs->tag = tag;
1049 
1050     /* Sanity-check the NCQ packet */
1051     if (tag != slot) {
1052         DPRINTF(port, "Warn: NCQ slot (%d) did not match the given tag (%d)\n",
1053                 slot, tag);
1054     }
1055 
1056     if (ncq_fis->aux0 || ncq_fis->aux1 || ncq_fis->aux2 || ncq_fis->aux3) {
1057         DPRINTF(port, "Warn: Attempt to use NCQ auxiliary fields.\n");
1058     }
1059     if (ncq_fis->prio || ncq_fis->icc) {
1060         DPRINTF(port, "Warn: Unsupported attempt to use PRIO/ICC fields\n");
1061     }
1062     if (ncq_fis->fua & NCQ_FIS_FUA_MASK) {
1063         DPRINTF(port, "Warn: Unsupported attempt to use Force Unit Access\n");
1064     }
1065     if (ncq_fis->tag & NCQ_FIS_RARC_MASK) {
1066         DPRINTF(port, "Warn: Unsupported attempt to use Rebuild Assist\n");
1067     }
1068 
1069     ncq_tfs->sector_count = ((uint16_t)ncq_fis->sector_count_high << 8) |
1070                                 ncq_fis->sector_count_low;
1071     size = ncq_tfs->sector_count * 512;
1072     ahci_populate_sglist(ad, &ncq_tfs->sglist, size, 0);
1073 
1074     if (ncq_tfs->sglist.size < size) {
1075         error_report("ahci: PRDT length for NCQ command (0x%zx) "
1076                      "is smaller than the requested size (0x%zx)",
1077                      ncq_tfs->sglist.size, size);
1078         qemu_sglist_destroy(&ncq_tfs->sglist);
1079         ncq_err(ncq_tfs);
1080         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_OVERFLOW);
1081         return;
1082     } else if (ncq_tfs->sglist.size != size) {
1083         DPRINTF(port, "Warn: PRDTL (0x%zx)"
1084                 " does not match requested size (0x%zx)",
1085                 ncq_tfs->sglist.size, size);
1086     }
1087 
1088     DPRINTF(port, "NCQ transfer LBA from %"PRId64" to %"PRId64", "
1089             "drive max %"PRId64"\n",
1090             ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 1,
1091             ide_state->nb_sectors - 1);
1092 
1093     execute_ncq_command(ncq_tfs);
1094 }
1095 
1096 static void handle_reg_h2d_fis(AHCIState *s, int port,
1097                                int slot, uint8_t *cmd_fis)
1098 {
1099     IDEState *ide_state = &s->dev[port].port.ifs[0];
1100     AHCICmdHdr *cmd = s->dev[port].cur_cmd;
1101     uint16_t opts = le16_to_cpu(cmd->opts);
1102 
1103     if (cmd_fis[1] & 0x0F) {
1104         DPRINTF(port, "Port Multiplier not supported."
1105                 " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1106                 cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1107         return;
1108     }
1109 
1110     if (cmd_fis[1] & 0x70) {
1111         DPRINTF(port, "Reserved flags set in H2D Register FIS."
1112                 " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n",
1113                 cmd_fis[0], cmd_fis[1], cmd_fis[2]);
1114         return;
1115     }
1116 
1117     if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {
1118         switch (s->dev[port].port_state) {
1119         case STATE_RUN:
1120             if (cmd_fis[15] & ATA_SRST) {
1121                 s->dev[port].port_state = STATE_RESET;
1122             }
1123             break;
1124         case STATE_RESET:
1125             if (!(cmd_fis[15] & ATA_SRST)) {
1126                 ahci_reset_port(s, port);
1127             }
1128             break;
1129         }
1130         return;
1131     }
1132 
1133     /* Check for NCQ command */
1134     if (is_ncq(cmd_fis[2])) {
1135         process_ncq_command(s, port, cmd_fis, slot);
1136         return;
1137     }
1138 
1139     /* Decompose the FIS:
1140      * AHCI does not interpret FIS packets, it only forwards them.
1141      * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.
1142      * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.
1143      *
1144      * ATA4 describes sector number for LBA28/CHS commands.
1145      * ATA6 describes sector number for LBA48 commands.
1146      * ATA8 deprecates CHS fully, describing only LBA28/48.
1147      *
1148      * We dutifully convert the FIS into IDE registers, and allow the
1149      * core layer to interpret them as needed. */
1150     ide_state->feature = cmd_fis[3];
1151     ide_state->sector = cmd_fis[4];      /* LBA 7:0 */
1152     ide_state->lcyl = cmd_fis[5];        /* LBA 15:8  */
1153     ide_state->hcyl = cmd_fis[6];        /* LBA 23:16 */
1154     ide_state->select = cmd_fis[7];      /* LBA 27:24 (LBA28) */
1155     ide_state->hob_sector = cmd_fis[8];  /* LBA 31:24 */
1156     ide_state->hob_lcyl = cmd_fis[9];    /* LBA 39:32 */
1157     ide_state->hob_hcyl = cmd_fis[10];   /* LBA 47:40 */
1158     ide_state->hob_feature = cmd_fis[11];
1159     ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
1160     /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */
1161     /* 15: Only valid when UPDATE_COMMAND not set. */
1162 
1163     /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
1164      * table to ide_state->io_buffer */
1165     if (opts & AHCI_CMD_ATAPI) {
1166         memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
1167         debug_print_fis(ide_state->io_buffer, 0x10);
1168         s->dev[port].done_atapi_packet = false;
1169         /* XXX send PIO setup FIS */
1170     }
1171 
1172     ide_state->error = 0;
1173 
1174     /* Reset transferred byte counter */
1175     cmd->status = 0;
1176 
1177     /* We're ready to process the command in FIS byte 2. */
1178     ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);
1179 }
1180 
1181 static int handle_cmd(AHCIState *s, int port, int slot)
1182 {
1183     IDEState *ide_state;
1184     uint64_t tbl_addr;
1185     AHCICmdHdr *cmd;
1186     uint8_t *cmd_fis;
1187     dma_addr_t cmd_len;
1188 
1189     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1190         /* Engine currently busy, try again later */
1191         DPRINTF(port, "engine busy\n");
1192         return -1;
1193     }
1194 
1195     if (!s->dev[port].lst) {
1196         DPRINTF(port, "error: lst not given but cmd handled");
1197         return -1;
1198     }
1199     cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];
1200     /* remember current slot handle for later */
1201     s->dev[port].cur_cmd = cmd;
1202 
1203     /* The device we are working for */
1204     ide_state = &s->dev[port].port.ifs[0];
1205     if (!ide_state->blk) {
1206         DPRINTF(port, "error: guest accessed unused port");
1207         return -1;
1208     }
1209 
1210     tbl_addr = le64_to_cpu(cmd->tbl_addr);
1211     cmd_len = 0x80;
1212     cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,
1213                              DMA_DIRECTION_FROM_DEVICE);
1214     if (!cmd_fis) {
1215         DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
1216         return -1;
1217     } else if (cmd_len != 0x80) {
1218         ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR);
1219         DPRINTF(port, "error: dma_memory_map failed: "
1220                 "(len(%02"PRIx64") != 0x80)\n",
1221                 cmd_len);
1222         goto out;
1223     }
1224     debug_print_fis(cmd_fis, 0x80);
1225 
1226     switch (cmd_fis[0]) {
1227         case SATA_FIS_TYPE_REGISTER_H2D:
1228             handle_reg_h2d_fis(s, port, slot, cmd_fis);
1229             break;
1230         default:
1231             DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
1232                           "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
1233                           cmd_fis[2]);
1234             break;
1235     }
1236 
1237 out:
1238     dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,
1239                      cmd_len);
1240 
1241     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1242         /* async command, complete later */
1243         s->dev[port].busy_slot = slot;
1244         return -1;
1245     }
1246 
1247     /* done handling the command */
1248     return 0;
1249 }
1250 
1251 /* DMA dev <-> ram */
1252 static void ahci_start_transfer(IDEDMA *dma)
1253 {
1254     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1255     IDEState *s = &ad->port.ifs[0];
1256     uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
1257     /* write == ram -> device */
1258     uint16_t opts = le16_to_cpu(ad->cur_cmd->opts);
1259     int is_write = opts & AHCI_CMD_WRITE;
1260     int is_atapi = opts & AHCI_CMD_ATAPI;
1261     int has_sglist = 0;
1262 
1263     if (is_atapi && !ad->done_atapi_packet) {
1264         /* already prepopulated iobuffer */
1265         ad->done_atapi_packet = true;
1266         size = 0;
1267         goto out;
1268     }
1269 
1270     if (ahci_dma_prepare_buf(dma, size)) {
1271         has_sglist = 1;
1272     }
1273 
1274     DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",
1275             is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",
1276             has_sglist ? "" : "o");
1277 
1278     if (has_sglist && size) {
1279         if (is_write) {
1280             dma_buf_write(s->data_ptr, size, &s->sg);
1281         } else {
1282             dma_buf_read(s->data_ptr, size, &s->sg);
1283         }
1284     }
1285 
1286 out:
1287     /* declare that we processed everything */
1288     s->data_ptr = s->data_end;
1289 
1290     /* Update number of transferred bytes, destroy sglist */
1291     ahci_commit_buf(dma, size);
1292 
1293     s->end_transfer_func(s);
1294 
1295     if (!(s->status & DRQ_STAT)) {
1296         /* done with PIO send/receive */
1297         ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));
1298     }
1299 }
1300 
1301 static void ahci_start_dma(IDEDMA *dma, IDEState *s,
1302                            BlockCompletionFunc *dma_cb)
1303 {
1304     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1305     DPRINTF(ad->port_no, "\n");
1306     s->io_buffer_offset = 0;
1307     dma_cb(s, 0);
1308 }
1309 
1310 static void ahci_restart_dma(IDEDMA *dma)
1311 {
1312     /* Nothing to do, ahci_start_dma already resets s->io_buffer_offset.  */
1313 }
1314 
1315 /**
1316  * Called in DMA R/W chains to read the PRDT, utilizing ahci_populate_sglist.
1317  * Not currently invoked by PIO R/W chains,
1318  * which invoke ahci_populate_sglist via ahci_start_transfer.
1319  */
1320 static int32_t ahci_dma_prepare_buf(IDEDMA *dma, int32_t limit)
1321 {
1322     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1323     IDEState *s = &ad->port.ifs[0];
1324 
1325     if (ahci_populate_sglist(ad, &s->sg, limit, s->io_buffer_offset) == -1) {
1326         DPRINTF(ad->port_no, "ahci_dma_prepare_buf failed.\n");
1327         return -1;
1328     }
1329     s->io_buffer_size = s->sg.size;
1330 
1331     DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
1332     return s->io_buffer_size;
1333 }
1334 
1335 /**
1336  * Destroys the scatter-gather list,
1337  * and updates the command header with a bytes-read value.
1338  * called explicitly via ahci_dma_rw_buf (ATAPI DMA),
1339  * and ahci_start_transfer (PIO R/W),
1340  * and called via callback from ide_dma_cb for DMA R/W paths.
1341  */
1342 static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes)
1343 {
1344     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1345     IDEState *s = &ad->port.ifs[0];
1346 
1347     tx_bytes += le32_to_cpu(ad->cur_cmd->status);
1348     ad->cur_cmd->status = cpu_to_le32(tx_bytes);
1349 
1350     qemu_sglist_destroy(&s->sg);
1351 }
1352 
1353 static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
1354 {
1355     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1356     IDEState *s = &ad->port.ifs[0];
1357     uint8_t *p = s->io_buffer + s->io_buffer_index;
1358     int l = s->io_buffer_size - s->io_buffer_index;
1359 
1360     if (ahci_populate_sglist(ad, &s->sg, l, s->io_buffer_offset)) {
1361         return 0;
1362     }
1363 
1364     if (is_write) {
1365         dma_buf_read(p, l, &s->sg);
1366     } else {
1367         dma_buf_write(p, l, &s->sg);
1368     }
1369 
1370     /* free sglist, update byte count */
1371     ahci_commit_buf(dma, l);
1372 
1373     s->io_buffer_index += l;
1374     s->io_buffer_offset += l;
1375 
1376     DPRINTF(ad->port_no, "len=%#x\n", l);
1377 
1378     return 1;
1379 }
1380 
1381 static void ahci_cmd_done(IDEDMA *dma)
1382 {
1383     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1384 
1385     DPRINTF(ad->port_no, "cmd done\n");
1386 
1387     /* update d2h status */
1388     ahci_write_fis_d2h(ad, NULL);
1389 
1390     if (!ad->check_bh) {
1391         /* maybe we still have something to process, check later */
1392         ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad);
1393         qemu_bh_schedule(ad->check_bh);
1394     }
1395 }
1396 
1397 static void ahci_irq_set(void *opaque, int n, int level)
1398 {
1399 }
1400 
1401 static const IDEDMAOps ahci_dma_ops = {
1402     .start_dma = ahci_start_dma,
1403     .restart_dma = ahci_restart_dma,
1404     .start_transfer = ahci_start_transfer,
1405     .prepare_buf = ahci_dma_prepare_buf,
1406     .commit_buf = ahci_commit_buf,
1407     .rw_buf = ahci_dma_rw_buf,
1408     .cmd_done = ahci_cmd_done,
1409 };
1410 
1411 void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports)
1412 {
1413     qemu_irq *irqs;
1414     int i;
1415 
1416     s->as = as;
1417     s->ports = ports;
1418     s->dev = g_new0(AHCIDevice, ports);
1419     ahci_reg_init(s);
1420     /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1421     memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s,
1422                           "ahci", AHCI_MEM_BAR_SIZE);
1423     memory_region_init_io(&s->idp, OBJECT(qdev), &ahci_idp_ops, s,
1424                           "ahci-idp", 32);
1425 
1426     irqs = qemu_allocate_irqs(ahci_irq_set, s, s->ports);
1427 
1428     for (i = 0; i < s->ports; i++) {
1429         AHCIDevice *ad = &s->dev[i];
1430 
1431         ide_bus_new(&ad->port, sizeof(ad->port), qdev, i, 1);
1432         ide_init2(&ad->port, irqs[i]);
1433 
1434         ad->hba = s;
1435         ad->port_no = i;
1436         ad->port.dma = &ad->dma;
1437         ad->port.dma->ops = &ahci_dma_ops;
1438         ide_register_restart_cb(&ad->port);
1439     }
1440 }
1441 
1442 void ahci_uninit(AHCIState *s)
1443 {
1444     g_free(s->dev);
1445 }
1446 
1447 void ahci_reset(AHCIState *s)
1448 {
1449     AHCIPortRegs *pr;
1450     int i;
1451 
1452     s->control_regs.irqstatus = 0;
1453     /* AHCI Enable (AE)
1454      * The implementation of this bit is dependent upon the value of the
1455      * CAP.SAM bit. If CAP.SAM is '0', then GHC.AE shall be read-write and
1456      * shall have a reset value of '0'. If CAP.SAM is '1', then AE shall be
1457      * read-only and shall have a reset value of '1'.
1458      *
1459      * We set HOST_CAP_AHCI so we must enable AHCI at reset.
1460      */
1461     s->control_regs.ghc = HOST_CTL_AHCI_EN;
1462 
1463     for (i = 0; i < s->ports; i++) {
1464         pr = &s->dev[i].port_regs;
1465         pr->irq_stat = 0;
1466         pr->irq_mask = 0;
1467         pr->scr_ctl = 0;
1468         pr->cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
1469         ahci_reset_port(s, i);
1470     }
1471 }
1472 
1473 static const VMStateDescription vmstate_ahci_device = {
1474     .name = "ahci port",
1475     .version_id = 1,
1476     .fields = (VMStateField[]) {
1477         VMSTATE_IDE_BUS(port, AHCIDevice),
1478         VMSTATE_IDE_DRIVE(port.ifs[0], AHCIDevice),
1479         VMSTATE_UINT32(port_state, AHCIDevice),
1480         VMSTATE_UINT32(finished, AHCIDevice),
1481         VMSTATE_UINT32(port_regs.lst_addr, AHCIDevice),
1482         VMSTATE_UINT32(port_regs.lst_addr_hi, AHCIDevice),
1483         VMSTATE_UINT32(port_regs.fis_addr, AHCIDevice),
1484         VMSTATE_UINT32(port_regs.fis_addr_hi, AHCIDevice),
1485         VMSTATE_UINT32(port_regs.irq_stat, AHCIDevice),
1486         VMSTATE_UINT32(port_regs.irq_mask, AHCIDevice),
1487         VMSTATE_UINT32(port_regs.cmd, AHCIDevice),
1488         VMSTATE_UINT32(port_regs.tfdata, AHCIDevice),
1489         VMSTATE_UINT32(port_regs.sig, AHCIDevice),
1490         VMSTATE_UINT32(port_regs.scr_stat, AHCIDevice),
1491         VMSTATE_UINT32(port_regs.scr_ctl, AHCIDevice),
1492         VMSTATE_UINT32(port_regs.scr_err, AHCIDevice),
1493         VMSTATE_UINT32(port_regs.scr_act, AHCIDevice),
1494         VMSTATE_UINT32(port_regs.cmd_issue, AHCIDevice),
1495         VMSTATE_BOOL(done_atapi_packet, AHCIDevice),
1496         VMSTATE_INT32(busy_slot, AHCIDevice),
1497         VMSTATE_BOOL(init_d2h_sent, AHCIDevice),
1498         VMSTATE_END_OF_LIST()
1499     },
1500 };
1501 
1502 static int ahci_state_post_load(void *opaque, int version_id)
1503 {
1504     int i;
1505     struct AHCIDevice *ad;
1506     AHCIState *s = opaque;
1507 
1508     for (i = 0; i < s->ports; i++) {
1509         ad = &s->dev[i];
1510 
1511         /* Only remap the CLB address if appropriate, disallowing a state
1512          * transition from 'on' to 'off' it should be consistent here. */
1513         if (ahci_cond_start_engines(ad, false) != 0) {
1514             return -1;
1515         }
1516 
1517         /*
1518          * If an error is present, ad->busy_slot will be valid and not -1.
1519          * In this case, an operation is waiting to resume and will re-check
1520          * for additional AHCI commands to execute upon completion.
1521          *
1522          * In the case where no error was present, busy_slot will be -1,
1523          * and we should check to see if there are additional commands waiting.
1524          */
1525         if (ad->busy_slot == -1) {
1526             check_cmd(s, i);
1527         } else {
1528             /* We are in the middle of a command, and may need to access
1529              * the command header in guest memory again. */
1530             if (ad->busy_slot < 0 || ad->busy_slot >= AHCI_MAX_CMDS) {
1531                 return -1;
1532             }
1533             ad->cur_cmd = &((AHCICmdHdr *)ad->lst)[ad->busy_slot];
1534         }
1535     }
1536 
1537     return 0;
1538 }
1539 
1540 const VMStateDescription vmstate_ahci = {
1541     .name = "ahci",
1542     .version_id = 1,
1543     .post_load = ahci_state_post_load,
1544     .fields = (VMStateField[]) {
1545         VMSTATE_STRUCT_VARRAY_POINTER_INT32(dev, AHCIState, ports,
1546                                      vmstate_ahci_device, AHCIDevice),
1547         VMSTATE_UINT32(control_regs.cap, AHCIState),
1548         VMSTATE_UINT32(control_regs.ghc, AHCIState),
1549         VMSTATE_UINT32(control_regs.irqstatus, AHCIState),
1550         VMSTATE_UINT32(control_regs.impl, AHCIState),
1551         VMSTATE_UINT32(control_regs.version, AHCIState),
1552         VMSTATE_UINT32(idp_index, AHCIState),
1553         VMSTATE_INT32_EQUAL(ports, AHCIState),
1554         VMSTATE_END_OF_LIST()
1555     },
1556 };
1557 
1558 #define TYPE_SYSBUS_AHCI "sysbus-ahci"
1559 #define SYSBUS_AHCI(obj) OBJECT_CHECK(SysbusAHCIState, (obj), TYPE_SYSBUS_AHCI)
1560 
1561 typedef struct SysbusAHCIState {
1562     /*< private >*/
1563     SysBusDevice parent_obj;
1564     /*< public >*/
1565 
1566     AHCIState ahci;
1567     uint32_t num_ports;
1568 } SysbusAHCIState;
1569 
1570 static const VMStateDescription vmstate_sysbus_ahci = {
1571     .name = "sysbus-ahci",
1572     .fields = (VMStateField[]) {
1573         VMSTATE_AHCI(ahci, SysbusAHCIState),
1574         VMSTATE_END_OF_LIST()
1575     },
1576 };
1577 
1578 static void sysbus_ahci_reset(DeviceState *dev)
1579 {
1580     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1581 
1582     ahci_reset(&s->ahci);
1583 }
1584 
1585 static void sysbus_ahci_realize(DeviceState *dev, Error **errp)
1586 {
1587     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1588     SysbusAHCIState *s = SYSBUS_AHCI(dev);
1589 
1590     ahci_init(&s->ahci, dev, &address_space_memory, s->num_ports);
1591 
1592     sysbus_init_mmio(sbd, &s->ahci.mem);
1593     sysbus_init_irq(sbd, &s->ahci.irq);
1594 }
1595 
1596 static Property sysbus_ahci_properties[] = {
1597     DEFINE_PROP_UINT32("num-ports", SysbusAHCIState, num_ports, 1),
1598     DEFINE_PROP_END_OF_LIST(),
1599 };
1600 
1601 static void sysbus_ahci_class_init(ObjectClass *klass, void *data)
1602 {
1603     DeviceClass *dc = DEVICE_CLASS(klass);
1604 
1605     dc->realize = sysbus_ahci_realize;
1606     dc->vmsd = &vmstate_sysbus_ahci;
1607     dc->props = sysbus_ahci_properties;
1608     dc->reset = sysbus_ahci_reset;
1609     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1610 }
1611 
1612 static const TypeInfo sysbus_ahci_info = {
1613     .name          = TYPE_SYSBUS_AHCI,
1614     .parent        = TYPE_SYS_BUS_DEVICE,
1615     .instance_size = sizeof(SysbusAHCIState),
1616     .class_init    = sysbus_ahci_class_init,
1617 };
1618 
1619 static void sysbus_ahci_register_types(void)
1620 {
1621     type_register_static(&sysbus_ahci_info);
1622 }
1623 
1624 type_init(sysbus_ahci_register_types)
1625 
1626 void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd)
1627 {
1628     AHCIPCIState *d = ICH_AHCI(dev);
1629     AHCIState *ahci = &d->ahci;
1630     int i;
1631 
1632     for (i = 0; i < ahci->ports; i++) {
1633         if (hd[i] == NULL) {
1634             continue;
1635         }
1636         ide_create_drive(&ahci->dev[i].port, 0, hd[i]);
1637     }
1638 
1639 }
1640