xref: /openbmc/qemu/hw/ide/ahci.c (revision 9c046d96d4d0d1fef89a30b1491775492082da9d)
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  * lspci dump of a ICH-9 real device in IDE mode (hopefully close enough):
24  *
25  * 00:1f.2 SATA controller [0106]: Intel Corporation 82801IR/IO/IH (ICH9R/DO/DH) 6 port SATA AHCI Controller [8086:2922] (rev 02) (prog-if 01 [AHCI 1.0])
26  *         Subsystem: Intel Corporation 82801IR/IO/IH (ICH9R/DO/DH) 6 port SATA AHCI Controller [8086:2922]
27  *         Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+
28  *         Status: Cap+ 66MHz+ UDF- FastB2B+ ParErr- DEVSEL=medium >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
29  *         Latency: 0
30  *         Interrupt: pin B routed to IRQ 222
31  *         Region 0: I/O ports at d000 [size=8]
32  *         Region 1: I/O ports at cc00 [size=4]
33  *         Region 2: I/O ports at c880 [size=8]
34  *         Region 3: I/O ports at c800 [size=4]
35  *         Region 4: I/O ports at c480 [size=32]
36  *         Region 5: Memory at febf9000 (32-bit, non-prefetchable) [size=2K]
37  *         Capabilities: [80] Message Signalled Interrupts: Mask- 64bit- Count=1/16 Enable+
38  *                 Address: fee0f00c  Data: 41d9
39  *         Capabilities: [70] Power Management version 3
40  *                 Flags: PMEClk- DSI- D1- D2- AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot+,D3cold-)
41  *                 Status: D0 PME-Enable- DSel=0 DScale=0 PME-
42  *         Capabilities: [a8] SATA HBA <?>
43  *         Capabilities: [b0] Vendor Specific Information <?>
44  *         Kernel driver in use: ahci
45  *         Kernel modules: ahci
46  * 00: 86 80 22 29 07 04 b0 02 02 01 06 01 00 00 00 00
47  * 10: 01 d0 00 00 01 cc 00 00 81 c8 00 00 01 c8 00 00
48  * 20: 81 c4 00 00 00 90 bf fe 00 00 00 00 86 80 22 29
49  * 30: 00 00 00 00 80 00 00 00 00 00 00 00 0f 02 00 00
50  * 40: 00 80 00 80 00 00 00 00 00 00 00 00 00 00 00 00
51  * 50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
52  * 60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
53  * 70: 01 a8 03 40 08 00 00 00 00 00 00 00 00 00 00 00
54  * 80: 05 70 09 00 0c f0 e0 fe d9 41 00 00 00 00 00 00
55  * 90: 40 00 0f 82 93 01 00 00 00 00 00 00 00 00 00 00
56  * a0: ac 00 00 00 0a 00 12 00 12 b0 10 00 48 00 00 00
57  * b0: 09 00 06 20 00 00 00 00 00 00 00 00 00 00 00 00
58  * c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
59  * d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
60  * e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
61  * f0: 00 00 00 00 00 00 00 00 86 0f 02 00 00 00 00 00
62  *
63  */
64 
65 #include <hw/hw.h>
66 #include <hw/msi.h>
67 #include <hw/pc.h>
68 #include <hw/pci.h>
69 
70 #include "monitor.h"
71 #include "dma.h"
72 #include "cpu-common.h"
73 #include "blockdev.h"
74 #include "internal.h"
75 #include <hw/ide/pci.h>
76 
77 /* #define DEBUG_AHCI */
78 
79 #ifdef DEBUG_AHCI
80 #define DPRINTF(port, fmt, ...) \
81 do { fprintf(stderr, "ahci: %s: [%d] ", __FUNCTION__, port); \
82      fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
83 #else
84 #define DPRINTF(port, fmt, ...) do {} while(0)
85 #endif
86 
87 #define AHCI_PCI_BAR              5
88 #define AHCI_MAX_PORTS            32
89 #define AHCI_MAX_SG               168 /* hardware max is 64K */
90 #define AHCI_DMA_BOUNDARY         0xffffffff
91 #define AHCI_USE_CLUSTERING       0
92 #define AHCI_MAX_CMDS             32
93 #define AHCI_CMD_SZ               32
94 #define AHCI_CMD_SLOT_SZ          (AHCI_MAX_CMDS * AHCI_CMD_SZ)
95 #define AHCI_RX_FIS_SZ            256
96 #define AHCI_CMD_TBL_CDB          0x40
97 #define AHCI_CMD_TBL_HDR_SZ       0x80
98 #define AHCI_CMD_TBL_SZ           (AHCI_CMD_TBL_HDR_SZ + (AHCI_MAX_SG * 16))
99 #define AHCI_CMD_TBL_AR_SZ        (AHCI_CMD_TBL_SZ * AHCI_MAX_CMDS)
100 #define AHCI_PORT_PRIV_DMA_SZ     (AHCI_CMD_SLOT_SZ + AHCI_CMD_TBL_AR_SZ + \
101                                    AHCI_RX_FIS_SZ)
102 
103 #define AHCI_IRQ_ON_SG            (1 << 31)
104 #define AHCI_CMD_ATAPI            (1 << 5)
105 #define AHCI_CMD_WRITE            (1 << 6)
106 #define AHCI_CMD_PREFETCH         (1 << 7)
107 #define AHCI_CMD_RESET            (1 << 8)
108 #define AHCI_CMD_CLR_BUSY         (1 << 10)
109 
110 #define RX_FIS_D2H_REG            0x40 /* offset of D2H Register FIS data */
111 #define RX_FIS_SDB                0x58 /* offset of SDB FIS data */
112 #define RX_FIS_UNK                0x60 /* offset of Unknown FIS data */
113 
114 /* global controller registers */
115 #define HOST_CAP                  0x00 /* host capabilities */
116 #define HOST_CTL                  0x04 /* global host control */
117 #define HOST_IRQ_STAT             0x08 /* interrupt status */
118 #define HOST_PORTS_IMPL           0x0c /* bitmap of implemented ports */
119 #define HOST_VERSION              0x10 /* AHCI spec. version compliancy */
120 
121 /* HOST_CTL bits */
122 #define HOST_CTL_RESET            (1 << 0)  /* reset controller; self-clear */
123 #define HOST_CTL_IRQ_EN           (1 << 1)  /* global IRQ enable */
124 #define HOST_CTL_AHCI_EN          (1 << 31) /* AHCI enabled */
125 
126 /* HOST_CAP bits */
127 #define HOST_CAP_SSC              (1 << 14) /* Slumber capable */
128 #define HOST_CAP_AHCI             (1 << 18) /* AHCI only */
129 #define HOST_CAP_CLO              (1 << 24) /* Command List Override support */
130 #define HOST_CAP_SSS              (1 << 27) /* Staggered Spin-up */
131 #define HOST_CAP_NCQ              (1 << 30) /* Native Command Queueing */
132 #define HOST_CAP_64               (1 << 31) /* PCI DAC (64-bit DMA) support */
133 
134 /* registers for each SATA port */
135 #define PORT_LST_ADDR             0x00 /* command list DMA addr */
136 #define PORT_LST_ADDR_HI          0x04 /* command list DMA addr hi */
137 #define PORT_FIS_ADDR             0x08 /* FIS rx buf addr */
138 #define PORT_FIS_ADDR_HI          0x0c /* FIS rx buf addr hi */
139 #define PORT_IRQ_STAT             0x10 /* interrupt status */
140 #define PORT_IRQ_MASK             0x14 /* interrupt enable/disable mask */
141 #define PORT_CMD                  0x18 /* port command */
142 #define PORT_TFDATA               0x20 /* taskfile data */
143 #define PORT_SIG                  0x24 /* device TF signature */
144 #define PORT_SCR_STAT             0x28 /* SATA phy register: SStatus */
145 #define PORT_SCR_CTL              0x2c /* SATA phy register: SControl */
146 #define PORT_SCR_ERR              0x30 /* SATA phy register: SError */
147 #define PORT_SCR_ACT              0x34 /* SATA phy register: SActive */
148 #define PORT_CMD_ISSUE            0x38 /* command issue */
149 #define PORT_RESERVED             0x3c /* reserved */
150 
151 /* PORT_IRQ_{STAT,MASK} bits */
152 #define PORT_IRQ_COLD_PRES        (1 << 31) /* cold presence detect */
153 #define PORT_IRQ_TF_ERR           (1 << 30) /* task file error */
154 #define PORT_IRQ_HBUS_ERR         (1 << 29) /* host bus fatal error */
155 #define PORT_IRQ_HBUS_DATA_ERR    (1 << 28) /* host bus data error */
156 #define PORT_IRQ_IF_ERR           (1 << 27) /* interface fatal error */
157 #define PORT_IRQ_IF_NONFATAL      (1 << 26) /* interface non-fatal error */
158 #define PORT_IRQ_OVERFLOW         (1 << 24) /* xfer exhausted available S/G */
159 #define PORT_IRQ_BAD_PMP          (1 << 23) /* incorrect port multiplier */
160 
161 #define PORT_IRQ_PHYRDY           (1 << 22) /* PhyRdy changed */
162 #define PORT_IRQ_DEV_ILCK         (1 << 7) /* device interlock */
163 #define PORT_IRQ_CONNECT          (1 << 6) /* port connect change status */
164 #define PORT_IRQ_SG_DONE          (1 << 5) /* descriptor processed */
165 #define PORT_IRQ_UNK_FIS          (1 << 4) /* unknown FIS rx'd */
166 #define PORT_IRQ_SDB_FIS          (1 << 3) /* Set Device Bits FIS rx'd */
167 #define PORT_IRQ_DMAS_FIS         (1 << 2) /* DMA Setup FIS rx'd */
168 #define PORT_IRQ_PIOS_FIS         (1 << 1) /* PIO Setup FIS rx'd */
169 #define PORT_IRQ_D2H_REG_FIS      (1 << 0) /* D2H Register FIS rx'd */
170 
171 #define PORT_IRQ_FREEZE           (PORT_IRQ_HBUS_ERR | PORT_IRQ_IF_ERR |   \
172                                    PORT_IRQ_CONNECT | PORT_IRQ_PHYRDY |    \
173                                    PORT_IRQ_UNK_FIS)
174 #define PORT_IRQ_ERROR            (PORT_IRQ_FREEZE | PORT_IRQ_TF_ERR |     \
175                                    PORT_IRQ_HBUS_DATA_ERR)
176 #define DEF_PORT_IRQ              (PORT_IRQ_ERROR | PORT_IRQ_SG_DONE |     \
177                                    PORT_IRQ_SDB_FIS | PORT_IRQ_DMAS_FIS |  \
178                                    PORT_IRQ_PIOS_FIS | PORT_IRQ_D2H_REG_FIS)
179 
180 /* PORT_CMD bits */
181 #define PORT_CMD_ATAPI            (1 << 24) /* Device is ATAPI */
182 #define PORT_CMD_LIST_ON          (1 << 15) /* cmd list DMA engine running */
183 #define PORT_CMD_FIS_ON           (1 << 14) /* FIS DMA engine running */
184 #define PORT_CMD_FIS_RX           (1 << 4) /* Enable FIS receive DMA engine */
185 #define PORT_CMD_CLO              (1 << 3) /* Command list override */
186 #define PORT_CMD_POWER_ON         (1 << 2) /* Power up device */
187 #define PORT_CMD_SPIN_UP          (1 << 1) /* Spin up device */
188 #define PORT_CMD_START            (1 << 0) /* Enable port DMA engine */
189 
190 #define PORT_CMD_ICC_MASK         (0xf << 28) /* i/f ICC state mask */
191 #define PORT_CMD_ICC_ACTIVE       (0x1 << 28) /* Put i/f in active state */
192 #define PORT_CMD_ICC_PARTIAL      (0x2 << 28) /* Put i/f in partial state */
193 #define PORT_CMD_ICC_SLUMBER      (0x6 << 28) /* Put i/f in slumber state */
194 
195 #define PORT_IRQ_STAT_DHRS        (1 << 0) /* Device to Host Register FIS */
196 #define PORT_IRQ_STAT_PSS         (1 << 1) /* PIO Setup FIS */
197 #define PORT_IRQ_STAT_DSS         (1 << 2) /* DMA Setup FIS */
198 #define PORT_IRQ_STAT_SDBS        (1 << 3) /* Set Device Bits */
199 #define PORT_IRQ_STAT_UFS         (1 << 4) /* Unknown FIS */
200 #define PORT_IRQ_STAT_DPS         (1 << 5) /* Descriptor Processed */
201 #define PORT_IRQ_STAT_PCS         (1 << 6) /* Port Connect Change Status */
202 #define PORT_IRQ_STAT_DMPS        (1 << 7) /* Device Mechanical Presence
203                                               Status */
204 #define PORT_IRQ_STAT_PRCS        (1 << 22) /* File Ready Status */
205 #define PORT_IRQ_STAT_IPMS        (1 << 23) /* Incorrect Port Multiplier
206                                                Status */
207 #define PORT_IRQ_STAT_OFS         (1 << 24) /* Overflow Status */
208 #define PORT_IRQ_STAT_INFS        (1 << 26) /* Interface Non-Fatal Error
209                                                Status */
210 #define PORT_IRQ_STAT_IFS         (1 << 27) /* Interface Fatal Error */
211 #define PORT_IRQ_STAT_HBDS        (1 << 28) /* Host Bus Data Error Status */
212 #define PORT_IRQ_STAT_HBFS        (1 << 29) /* Host Bus Fatal Error Status */
213 #define PORT_IRQ_STAT_TFES        (1 << 30) /* Task File Error Status */
214 #define PORT_IRQ_STAT_CPDS        (1 << 31) /* Code Port Detect Status */
215 
216 /* ap->flags bits */
217 #define AHCI_FLAG_NO_NCQ                  (1 << 24)
218 #define AHCI_FLAG_IGN_IRQ_IF_ERR          (1 << 25) /* ignore IRQ_IF_ERR */
219 #define AHCI_FLAG_HONOR_PI                (1 << 26) /* honor PORTS_IMPL */
220 #define AHCI_FLAG_IGN_SERR_INTERNAL       (1 << 27) /* ignore SERR_INTERNAL */
221 #define AHCI_FLAG_32BIT_ONLY              (1 << 28) /* force 32bit */
222 
223 #define ATA_SRST                          (1 << 2)  /* software reset */
224 
225 #define STATE_RUN                         0
226 #define STATE_RESET                       1
227 
228 #define SATA_SCR_SSTATUS_DET_NODEV        0x0
229 #define SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP 0x3
230 
231 #define SATA_SCR_SSTATUS_SPD_NODEV        0x00
232 #define SATA_SCR_SSTATUS_SPD_GEN1         0x10
233 
234 #define SATA_SCR_SSTATUS_IPM_NODEV        0x000
235 #define SATA_SCR_SSTATUS_IPM_ACTIVE       0X100
236 
237 #define AHCI_SCR_SCTL_DET                 0xf
238 
239 #define SATA_FIS_TYPE_REGISTER_H2D        0x27
240 #define SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER 0x80
241 
242 #define AHCI_CMD_HDR_CMD_FIS_LEN           0x1f
243 #define AHCI_CMD_HDR_PRDT_LEN              16
244 
245 #define SATA_SIGNATURE_CDROM               0xeb140000
246 #define SATA_SIGNATURE_DISK                0x00000101
247 
248 #define AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR 0x20
249                                             /* Shouldn't this be 0x2c? */
250 
251 #define SATA_PORTS                         4
252 
253 #define AHCI_PORT_REGS_START_ADDR          0x100
254 #define AHCI_PORT_REGS_END_ADDR (AHCI_PORT_REGS_START_ADDR + SATA_PORTS * 0x80)
255 #define AHCI_PORT_ADDR_OFFSET_MASK         0x7f
256 
257 #define AHCI_NUM_COMMAND_SLOTS             31
258 #define AHCI_SUPPORTED_SPEED               20
259 #define AHCI_SUPPORTED_SPEED_GEN1          1
260 #define AHCI_VERSION_1_0                   0x10000
261 
262 #define AHCI_PROGMODE_MAJOR_REV_1          1
263 
264 #define AHCI_COMMAND_TABLE_ACMD            0x40
265 
266 #define IDE_FEATURE_DMA                    1
267 
268 #define READ_FPDMA_QUEUED                  0x60
269 #define WRITE_FPDMA_QUEUED                 0x61
270 
271 #define RES_FIS_DSFIS                      0x00
272 #define RES_FIS_PSFIS                      0x20
273 #define RES_FIS_RFIS                       0x40
274 #define RES_FIS_SDBFIS                     0x58
275 #define RES_FIS_UFIS                       0x60
276 
277 typedef struct AHCIControlRegs {
278     uint32_t    cap;
279     uint32_t    ghc;
280     uint32_t    irqstatus;
281     uint32_t    impl;
282     uint32_t    version;
283 } AHCIControlRegs;
284 
285 typedef struct AHCIPortRegs {
286     uint32_t    lst_addr;
287     uint32_t    lst_addr_hi;
288     uint32_t    fis_addr;
289     uint32_t    fis_addr_hi;
290     uint32_t    irq_stat;
291     uint32_t    irq_mask;
292     uint32_t    cmd;
293     uint32_t    unused0;
294     uint32_t    tfdata;
295     uint32_t    sig;
296     uint32_t    scr_stat;
297     uint32_t    scr_ctl;
298     uint32_t    scr_err;
299     uint32_t    scr_act;
300     uint32_t    cmd_issue;
301     uint32_t    reserved;
302 } AHCIPortRegs;
303 
304 typedef struct AHCICmdHdr {
305     uint32_t    opts;
306     uint32_t    status;
307     uint64_t    tbl_addr;
308     uint32_t    reserved[4];
309 } __attribute__ ((packed)) AHCICmdHdr;
310 
311 typedef struct AHCI_SG {
312     uint64_t    addr;
313     uint32_t    reserved;
314     uint32_t    flags_size;
315 } __attribute__ ((packed)) AHCI_SG;
316 
317 typedef struct AHCIDevice AHCIDevice;
318 
319 typedef struct NCQTransferState {
320     AHCIDevice *drive;
321     BlockDriverAIOCB *aiocb;
322     QEMUSGList sglist;
323     int is_read;
324     uint16_t sector_count;
325     uint64_t lba;
326     uint8_t tag;
327     int slot;
328     int used;
329 } NCQTransferState;
330 
331 struct AHCIDevice {
332     IDEDMA dma;
333     IDEBus port;
334     int port_no;
335     uint32_t port_state;
336     uint32_t finished;
337     AHCIPortRegs port_regs;
338     struct AHCIState *hba;
339     QEMUBH *check_bh;
340     uint8_t *lst;
341     uint8_t *res_fis;
342     int dma_status;
343     int done_atapi_packet;
344     int busy_slot;
345     BlockDriverCompletionFunc *dma_cb;
346     AHCICmdHdr *cur_cmd;
347     NCQTransferState ncq_tfs[AHCI_MAX_CMDS];
348 };
349 
350 typedef struct AHCIState {
351     AHCIDevice dev[SATA_PORTS];
352     AHCIControlRegs control_regs;
353     int mem;
354     qemu_irq irq;
355 } AHCIState;
356 
357 typedef struct AHCIPCIState {
358     PCIDevice card;
359     AHCIState ahci;
360 } AHCIPCIState;
361 
362 typedef struct NCQFrame {
363     uint8_t fis_type;
364     uint8_t c;
365     uint8_t command;
366     uint8_t sector_count_low;
367     uint8_t lba0;
368     uint8_t lba1;
369     uint8_t lba2;
370     uint8_t fua;
371     uint8_t lba3;
372     uint8_t lba4;
373     uint8_t lba5;
374     uint8_t sector_count_high;
375     uint8_t tag;
376     uint8_t reserved5;
377     uint8_t reserved6;
378     uint8_t control;
379     uint8_t reserved7;
380     uint8_t reserved8;
381     uint8_t reserved9;
382     uint8_t reserved10;
383 } __attribute__ ((packed)) NCQFrame;
384 
385 static void check_cmd(AHCIState *s, int port);
386 static int handle_cmd(AHCIState *s,int port,int slot);
387 static void ahci_reset_port(AHCIState *s, int port);
388 static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis);
389 
390 static uint32_t  ahci_port_read(AHCIState *s, int port, int offset)
391 {
392     uint32_t val;
393     AHCIPortRegs *pr;
394     pr = &s->dev[port].port_regs;
395 
396     switch (offset) {
397     case PORT_LST_ADDR:
398         val = pr->lst_addr;
399         break;
400     case PORT_LST_ADDR_HI:
401         val = pr->lst_addr_hi;
402         break;
403     case PORT_FIS_ADDR:
404         val = pr->fis_addr;
405         break;
406     case PORT_FIS_ADDR_HI:
407         val = pr->fis_addr_hi;
408         break;
409     case PORT_IRQ_STAT:
410         val = pr->irq_stat;
411         break;
412     case PORT_IRQ_MASK:
413         val = pr->irq_mask;
414         break;
415     case PORT_CMD:
416         val = pr->cmd;
417         break;
418     case PORT_TFDATA:
419         val = ((uint16_t)s->dev[port].port.ifs[0].error << 8) |
420               s->dev[port].port.ifs[0].status;
421         break;
422     case PORT_SIG:
423         val = pr->sig;
424         break;
425     case PORT_SCR_STAT:
426         if (s->dev[port].port.ifs[0].bs) {
427             val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP |
428                   SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE;
429         } else {
430             val = SATA_SCR_SSTATUS_DET_NODEV;
431         }
432         break;
433     case PORT_SCR_CTL:
434         val = pr->scr_ctl;
435         break;
436     case PORT_SCR_ERR:
437         val = pr->scr_err;
438         break;
439     case PORT_SCR_ACT:
440         pr->scr_act &= ~s->dev[port].finished;
441         s->dev[port].finished = 0;
442         val = pr->scr_act;
443         break;
444     case PORT_CMD_ISSUE:
445         val = pr->cmd_issue;
446         break;
447     case PORT_RESERVED:
448     default:
449         val = 0;
450     }
451     DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
452     return val;
453 
454 }
455 
456 static void ahci_irq_raise(AHCIState *s, AHCIDevice *dev)
457 {
458     struct AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
459 
460     DPRINTF(0, "raise irq\n");
461 
462     if (msi_enabled(&d->card)) {
463         msi_notify(&d->card, 0);
464     } else {
465         qemu_irq_raise(s->irq);
466     }
467 }
468 
469 static void ahci_irq_lower(AHCIState *s, AHCIDevice *dev)
470 {
471     struct AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);
472 
473     DPRINTF(0, "lower irq\n");
474 
475     if (!msi_enabled(&d->card)) {
476         qemu_irq_lower(s->irq);
477     }
478 }
479 
480 static void ahci_check_irq(AHCIState *s)
481 {
482     int i;
483 
484     DPRINTF(-1, "check irq %#x\n", s->control_regs.irqstatus);
485 
486     for (i = 0; i < SATA_PORTS; i++) {
487         AHCIPortRegs *pr = &s->dev[i].port_regs;
488         if (pr->irq_stat & pr->irq_mask) {
489             s->control_regs.irqstatus |= (1 << i);
490         }
491     }
492 
493     if (s->control_regs.irqstatus &&
494         (s->control_regs.ghc & HOST_CTL_IRQ_EN)) {
495             ahci_irq_raise(s, NULL);
496     } else {
497         ahci_irq_lower(s, NULL);
498     }
499 }
500 
501 static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d,
502                              int irq_type)
503 {
504     DPRINTF(d->port_no, "trigger irq %#x -> %x\n",
505             irq_type, d->port_regs.irq_mask & irq_type);
506 
507     d->port_regs.irq_stat |= irq_type;
508     ahci_check_irq(s);
509 }
510 
511 static void map_page(uint8_t **ptr, uint64_t addr, uint32_t wanted)
512 {
513     target_phys_addr_t len = wanted;
514 
515     if (*ptr) {
516         cpu_physical_memory_unmap(*ptr, 1, len, len);
517     }
518 
519     *ptr = cpu_physical_memory_map(addr, &len, 1);
520     if (len < wanted) {
521         cpu_physical_memory_unmap(*ptr, 1, len, len);
522         *ptr = NULL;
523     }
524 }
525 
526 static void  ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)
527 {
528     AHCIPortRegs *pr = &s->dev[port].port_regs;
529 
530     DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);
531     switch (offset) {
532         case PORT_LST_ADDR:
533             pr->lst_addr = val;
534             map_page(&s->dev[port].lst,
535                      ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
536             s->dev[port].cur_cmd = NULL;
537             break;
538         case PORT_LST_ADDR_HI:
539             pr->lst_addr_hi = val;
540             map_page(&s->dev[port].lst,
541                      ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024);
542             s->dev[port].cur_cmd = NULL;
543             break;
544         case PORT_FIS_ADDR:
545             pr->fis_addr = val;
546             map_page(&s->dev[port].res_fis,
547                      ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
548             break;
549         case PORT_FIS_ADDR_HI:
550             pr->fis_addr_hi = val;
551             map_page(&s->dev[port].res_fis,
552                      ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256);
553             break;
554         case PORT_IRQ_STAT:
555             pr->irq_stat &= ~val;
556             break;
557         case PORT_IRQ_MASK:
558             pr->irq_mask = val & 0xfdc000ff;
559             ahci_check_irq(s);
560             break;
561         case PORT_CMD:
562             pr->cmd = val & ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON);
563 
564             if (pr->cmd & PORT_CMD_START) {
565                 pr->cmd |= PORT_CMD_LIST_ON;
566             }
567 
568             if (pr->cmd & PORT_CMD_FIS_RX) {
569                 pr->cmd |= PORT_CMD_FIS_ON;
570             }
571 
572             check_cmd(s, port);
573             break;
574         case PORT_TFDATA:
575             s->dev[port].port.ifs[0].error = (val >> 8) & 0xff;
576             s->dev[port].port.ifs[0].status = val & 0xff;
577             break;
578         case PORT_SIG:
579             pr->sig = val;
580             break;
581         case PORT_SCR_STAT:
582             pr->scr_stat = val;
583             break;
584         case PORT_SCR_CTL:
585             if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&
586                 ((val & AHCI_SCR_SCTL_DET) == 0)) {
587                 ahci_reset_port(s, port);
588             }
589             pr->scr_ctl = val;
590             break;
591         case PORT_SCR_ERR:
592             pr->scr_err &= ~val;
593             break;
594         case PORT_SCR_ACT:
595             /* RW1 */
596             pr->scr_act |= val;
597             break;
598         case PORT_CMD_ISSUE:
599             pr->cmd_issue |= val;
600             check_cmd(s, port);
601             break;
602         default:
603             break;
604     }
605 }
606 
607 static uint32_t ahci_mem_readl(void *ptr, target_phys_addr_t addr)
608 {
609     AHCIState *s = ptr;
610     uint32_t val = 0;
611 
612     addr = addr & 0xfff;
613     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
614         switch (addr) {
615         case HOST_CAP:
616             val = s->control_regs.cap;
617             break;
618         case HOST_CTL:
619             val = s->control_regs.ghc;
620             break;
621         case HOST_IRQ_STAT:
622             val = s->control_regs.irqstatus;
623             break;
624         case HOST_PORTS_IMPL:
625             val = s->control_regs.impl;
626             break;
627         case HOST_VERSION:
628             val = s->control_regs.version;
629             break;
630         }
631 
632         DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val);
633     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
634                (addr < AHCI_PORT_REGS_END_ADDR)) {
635         val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
636                              addr & AHCI_PORT_ADDR_OFFSET_MASK);
637     }
638 
639     return val;
640 }
641 
642 
643 
644 static void ahci_mem_writel(void *ptr, target_phys_addr_t addr, uint32_t val)
645 {
646     AHCIState *s = ptr;
647     addr = addr & 0xfff;
648 
649     /* Only aligned reads are allowed on AHCI */
650     if (addr & 3) {
651         fprintf(stderr, "ahci: Mis-aligned write to addr 0x"
652                 TARGET_FMT_plx "\n", addr);
653         return;
654     }
655 
656     if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {
657         DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val);
658 
659         switch (addr) {
660             case HOST_CAP: /* R/WO, RO */
661                 /* FIXME handle R/WO */
662                 break;
663             case HOST_CTL: /* R/W */
664                 if (val & HOST_CTL_RESET) {
665                     DPRINTF(-1, "HBA Reset\n");
666                     /* FIXME reset? */
667                 } else {
668                     s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;
669                     ahci_check_irq(s);
670                 }
671                 break;
672             case HOST_IRQ_STAT: /* R/WC, RO */
673                 s->control_regs.irqstatus &= ~val;
674                 ahci_check_irq(s);
675                 break;
676             case HOST_PORTS_IMPL: /* R/WO, RO */
677                 /* FIXME handle R/WO */
678                 break;
679             case HOST_VERSION: /* RO */
680                 /* FIXME report write? */
681                 break;
682             default:
683                 DPRINTF(-1, "write to unknown register 0x%x\n", (unsigned)addr);
684         }
685     } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&
686                (addr < AHCI_PORT_REGS_END_ADDR)) {
687         ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,
688                         addr & AHCI_PORT_ADDR_OFFSET_MASK, val);
689     }
690 
691 }
692 
693 static CPUReadMemoryFunc * const ahci_readfn[3]={
694     ahci_mem_readl,
695     ahci_mem_readl,
696     ahci_mem_readl
697 };
698 
699 static CPUWriteMemoryFunc * const ahci_writefn[3]={
700     ahci_mem_writel,
701     ahci_mem_writel,
702     ahci_mem_writel
703 };
704 
705 static void ahci_reg_init(AHCIState *s)
706 {
707     int i;
708 
709     s->control_regs.cap = (SATA_PORTS - 1) |
710                           (AHCI_NUM_COMMAND_SLOTS << 8) |
711                           (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) |
712                           HOST_CAP_NCQ | HOST_CAP_AHCI;
713 
714     s->control_regs.impl = (1 << SATA_PORTS) - 1;
715 
716     s->control_regs.version = AHCI_VERSION_1_0;
717 
718     for (i = 0; i < SATA_PORTS; i++) {
719         s->dev[i].port_state = STATE_RUN;
720     }
721 }
722 
723 static uint32_t read_from_sglist(uint8_t *buffer, uint32_t len,
724                                  QEMUSGList *sglist)
725 {
726     uint32_t i = 0;
727     uint32_t total = 0, once;
728     ScatterGatherEntry *cur_prd;
729     uint32_t sgcount;
730 
731     cur_prd = sglist->sg;
732     sgcount = sglist->nsg;
733     for (i = 0; len && sgcount; i++) {
734         once = MIN(cur_prd->len, len);
735         cpu_physical_memory_read(cur_prd->base, buffer, once);
736         cur_prd++;
737         sgcount--;
738         len -= once;
739         buffer += once;
740         total += once;
741     }
742 
743     return total;
744 }
745 
746 static uint32_t write_to_sglist(uint8_t *buffer, uint32_t len,
747                                 QEMUSGList *sglist)
748 {
749     uint32_t i = 0;
750     uint32_t total = 0, once;
751     ScatterGatherEntry *cur_prd;
752     uint32_t sgcount;
753 
754     DPRINTF(-1, "total: 0x%x bytes\n", len);
755 
756     cur_prd = sglist->sg;
757     sgcount = sglist->nsg;
758     for (i = 0; len && sgcount; i++) {
759         once = MIN(cur_prd->len, len);
760         DPRINTF(-1, "write 0x%x bytes to 0x%lx\n", once, (long)cur_prd->base);
761         cpu_physical_memory_write(cur_prd->base, buffer, once);
762         cur_prd++;
763         sgcount--;
764         len -= once;
765         buffer += once;
766         total += once;
767     }
768 
769     return total;
770 }
771 
772 static void check_cmd(AHCIState *s, int port)
773 {
774     AHCIPortRegs *pr = &s->dev[port].port_regs;
775     int slot;
776 
777     if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) {
778         for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) {
779             if ((pr->cmd_issue & (1 << slot)) &&
780                 !handle_cmd(s, port, slot)) {
781                 pr->cmd_issue &= ~(1 << slot);
782             }
783         }
784     }
785 }
786 
787 static void ahci_check_cmd_bh(void *opaque)
788 {
789     AHCIDevice *ad = opaque;
790 
791     qemu_bh_delete(ad->check_bh);
792     ad->check_bh = NULL;
793 
794     if ((ad->busy_slot != -1) &&
795         !(ad->port.ifs[0].status & (BUSY_STAT|DRQ_STAT))) {
796         /* no longer busy */
797         ad->port_regs.cmd_issue &= ~(1 << ad->busy_slot);
798         ad->busy_slot = -1;
799     }
800 
801     check_cmd(ad->hba, ad->port_no);
802 }
803 
804 static void ahci_reset_port(AHCIState *s, int port)
805 {
806     AHCIDevice *d = &s->dev[port];
807     AHCIPortRegs *pr = &d->port_regs;
808     IDEState *ide_state = &d->port.ifs[0];
809     uint8_t init_fis[0x20];
810     int i;
811 
812     DPRINTF(port, "reset port\n");
813 
814     ide_bus_reset(&d->port);
815     ide_state->ncq_queues = AHCI_MAX_CMDS;
816 
817     pr->irq_stat = 0;
818     pr->irq_mask = 0;
819     pr->scr_stat = 0;
820     pr->scr_ctl = 0;
821     pr->scr_err = 0;
822     pr->scr_act = 0;
823     d->busy_slot = -1;
824 
825     ide_state = &s->dev[port].port.ifs[0];
826     if (!ide_state->bs) {
827         return;
828     }
829 
830     /* reset ncq queue */
831     for (i = 0; i < AHCI_MAX_CMDS; i++) {
832         NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[i];
833         if (!ncq_tfs->used) {
834             continue;
835         }
836 
837         if (ncq_tfs->aiocb) {
838             bdrv_aio_cancel(ncq_tfs->aiocb);
839             ncq_tfs->aiocb = NULL;
840         }
841 
842         qemu_sglist_destroy(&ncq_tfs->sglist);
843         ncq_tfs->used = 0;
844     }
845 
846     memset(init_fis, 0, sizeof(init_fis));
847     s->dev[port].port_state = STATE_RUN;
848     if (!ide_state->bs) {
849         s->dev[port].port_regs.sig = 0;
850         ide_state->status = SEEK_STAT | WRERR_STAT;
851     } else if (ide_state->drive_kind == IDE_CD) {
852         s->dev[port].port_regs.sig = SATA_SIGNATURE_CDROM;
853         ide_state->lcyl = 0x14;
854         ide_state->hcyl = 0xeb;
855         DPRINTF(port, "set lcyl = %d\n", ide_state->lcyl);
856         init_fis[5] = ide_state->lcyl;
857         init_fis[6] = ide_state->hcyl;
858         ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT;
859     } else {
860         s->dev[port].port_regs.sig = SATA_SIGNATURE_DISK;
861         ide_state->status = SEEK_STAT | WRERR_STAT;
862     }
863 
864     ide_state->error = 1;
865     init_fis[4] = 1;
866     init_fis[12] = 1;
867     ahci_write_fis_d2h(d, init_fis);
868 }
869 
870 static void debug_print_fis(uint8_t *fis, int cmd_len)
871 {
872 #ifdef DEBUG_AHCI
873     int i;
874 
875     fprintf(stderr, "fis:");
876     for (i = 0; i < cmd_len; i++) {
877         if ((i & 0xf) == 0) {
878             fprintf(stderr, "\n%02x:",i);
879         }
880         fprintf(stderr, "%02x ",fis[i]);
881     }
882     fprintf(stderr, "\n");
883 #endif
884 }
885 
886 static void ahci_write_fis_sdb(AHCIState *s, int port, uint32_t finished)
887 {
888     AHCIPortRegs *pr = &s->dev[port].port_regs;
889     IDEState *ide_state;
890     uint8_t *sdb_fis;
891 
892     if (!s->dev[port].res_fis ||
893         !(pr->cmd & PORT_CMD_FIS_RX)) {
894         return;
895     }
896 
897     sdb_fis = &s->dev[port].res_fis[RES_FIS_SDBFIS];
898     ide_state = &s->dev[port].port.ifs[0];
899 
900     /* clear memory */
901     *(uint32_t*)sdb_fis = 0;
902 
903     /* write values */
904     sdb_fis[0] = ide_state->error;
905     sdb_fis[2] = ide_state->status & 0x77;
906     s->dev[port].finished |= finished;
907     *(uint32_t*)(sdb_fis + 4) = cpu_to_le32(s->dev[port].finished);
908 
909     ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_STAT_SDBS);
910 }
911 
912 static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
913 {
914     AHCIPortRegs *pr = &ad->port_regs;
915     uint8_t *d2h_fis;
916     int i;
917     target_phys_addr_t cmd_len = 0x80;
918     int cmd_mapped = 0;
919 
920     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
921         return;
922     }
923 
924     if (!cmd_fis) {
925         /* map cmd_fis */
926         uint64_t tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
927         cmd_fis = cpu_physical_memory_map(tbl_addr, &cmd_len, 0);
928         cmd_mapped = 1;
929     }
930 
931     d2h_fis = &ad->res_fis[RES_FIS_RFIS];
932 
933     d2h_fis[0] = 0x34;
934     d2h_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0);
935     d2h_fis[2] = ad->port.ifs[0].status;
936     d2h_fis[3] = ad->port.ifs[0].error;
937 
938     d2h_fis[4] = cmd_fis[4];
939     d2h_fis[5] = cmd_fis[5];
940     d2h_fis[6] = cmd_fis[6];
941     d2h_fis[7] = cmd_fis[7];
942     d2h_fis[8] = cmd_fis[8];
943     d2h_fis[9] = cmd_fis[9];
944     d2h_fis[10] = cmd_fis[10];
945     d2h_fis[11] = cmd_fis[11];
946     d2h_fis[12] = cmd_fis[12];
947     d2h_fis[13] = cmd_fis[13];
948     for (i = 14; i < 0x20; i++) {
949         d2h_fis[i] = 0;
950     }
951 
952     if (d2h_fis[2] & ERR_STAT) {
953         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_TFES);
954     }
955 
956     ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS);
957 
958     if (cmd_mapped) {
959         cpu_physical_memory_unmap(cmd_fis, 0, cmd_len, cmd_len);
960     }
961 }
962 
963 static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
964 {
965     AHCICmdHdr *cmd = ad->cur_cmd;
966     uint32_t opts = le32_to_cpu(cmd->opts);
967     uint64_t prdt_addr = le64_to_cpu(cmd->tbl_addr) + 0x80;
968     int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN;
969     target_phys_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));
970     target_phys_addr_t real_prdt_len = prdt_len;
971     uint8_t *prdt;
972     int i;
973     int r = 0;
974 
975     if (!sglist_alloc_hint) {
976         DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);
977         return -1;
978     }
979 
980     /* map PRDT */
981     if (!(prdt = cpu_physical_memory_map(prdt_addr, &prdt_len, 0))){
982         DPRINTF(ad->port_no, "map failed\n");
983         return -1;
984     }
985 
986     if (prdt_len < real_prdt_len) {
987         DPRINTF(ad->port_no, "mapped less than expected\n");
988         r = -1;
989         goto out;
990     }
991 
992     /* Get entries in the PRDT, init a qemu sglist accordingly */
993     if (sglist_alloc_hint > 0) {
994         AHCI_SG *tbl = (AHCI_SG *)prdt;
995 
996         qemu_sglist_init(sglist, sglist_alloc_hint);
997         for (i = 0; i < sglist_alloc_hint; i++) {
998             /* flags_size is zero-based */
999             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
1000                             le32_to_cpu(tbl[i].flags_size) + 1);
1001         }
1002     }
1003 
1004 out:
1005     cpu_physical_memory_unmap(prdt, 0, prdt_len, prdt_len);
1006     return r;
1007 }
1008 
1009 static void ncq_cb(void *opaque, int ret)
1010 {
1011     NCQTransferState *ncq_tfs = (NCQTransferState *)opaque;
1012     IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
1013 
1014     /* Clear bit for this tag in SActive */
1015     ncq_tfs->drive->port_regs.scr_act &= ~(1 << ncq_tfs->tag);
1016 
1017     if (ret < 0) {
1018         /* error */
1019         ide_state->error = ABRT_ERR;
1020         ide_state->status = READY_STAT | ERR_STAT;
1021         ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
1022     } else {
1023         ide_state->status = READY_STAT | SEEK_STAT;
1024     }
1025 
1026     ahci_write_fis_sdb(ncq_tfs->drive->hba, ncq_tfs->drive->port_no,
1027                        (1 << ncq_tfs->tag));
1028 
1029     DPRINTF(ncq_tfs->drive->port_no, "NCQ transfer tag %d finished\n",
1030             ncq_tfs->tag);
1031 
1032     qemu_sglist_destroy(&ncq_tfs->sglist);
1033     ncq_tfs->used = 0;
1034 }
1035 
1036 static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
1037                                 int slot)
1038 {
1039     NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;
1040     uint8_t tag = ncq_fis->tag >> 3;
1041     NCQTransferState *ncq_tfs = &s->dev[port].ncq_tfs[tag];
1042 
1043     if (ncq_tfs->used) {
1044         /* error - already in use */
1045         fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);
1046         return;
1047     }
1048 
1049     ncq_tfs->used = 1;
1050     ncq_tfs->drive = &s->dev[port];
1051     ncq_tfs->slot = slot;
1052     ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |
1053                    ((uint64_t)ncq_fis->lba4 << 32) |
1054                    ((uint64_t)ncq_fis->lba3 << 24) |
1055                    ((uint64_t)ncq_fis->lba2 << 16) |
1056                    ((uint64_t)ncq_fis->lba1 << 8) |
1057                    (uint64_t)ncq_fis->lba0;
1058 
1059     /* Note: We calculate the sector count, but don't currently rely on it.
1060      * The total size of the DMA buffer tells us the transfer size instead. */
1061     ncq_tfs->sector_count = ((uint16_t)ncq_fis->sector_count_high << 8) |
1062                                 ncq_fis->sector_count_low;
1063 
1064     DPRINTF(port, "NCQ transfer LBA from %ld to %ld, drive max %ld\n",
1065             ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 2,
1066             s->dev[port].port.ifs[0].nb_sectors - 1);
1067 
1068     ahci_populate_sglist(&s->dev[port], &ncq_tfs->sglist);
1069     ncq_tfs->tag = tag;
1070 
1071     switch(ncq_fis->command) {
1072         case READ_FPDMA_QUEUED:
1073             DPRINTF(port, "NCQ reading %d sectors from LBA %ld, tag %d\n",
1074                     ncq_tfs->sector_count-1, ncq_tfs->lba, ncq_tfs->tag);
1075             ncq_tfs->is_read = 1;
1076 
1077             DPRINTF(port, "tag %d aio read %ld\n", ncq_tfs->tag, ncq_tfs->lba);
1078             ncq_tfs->aiocb = dma_bdrv_read(ncq_tfs->drive->port.ifs[0].bs,
1079                                            &ncq_tfs->sglist, ncq_tfs->lba,
1080                                            ncq_cb, ncq_tfs);
1081             break;
1082         case WRITE_FPDMA_QUEUED:
1083             DPRINTF(port, "NCQ writing %d sectors to LBA %ld, tag %d\n",
1084                     ncq_tfs->sector_count-1, ncq_tfs->lba, ncq_tfs->tag);
1085             ncq_tfs->is_read = 0;
1086 
1087             DPRINTF(port, "tag %d aio write %ld\n", ncq_tfs->tag, ncq_tfs->lba);
1088             ncq_tfs->aiocb = dma_bdrv_write(ncq_tfs->drive->port.ifs[0].bs,
1089                                             &ncq_tfs->sglist, ncq_tfs->lba,
1090                                             ncq_cb, ncq_tfs);
1091             break;
1092         default:
1093             DPRINTF(port, "error: tried to process non-NCQ command as NCQ\n");
1094             qemu_sglist_destroy(&ncq_tfs->sglist);
1095             break;
1096     }
1097 }
1098 
1099 static int handle_cmd(AHCIState *s, int port, int slot)
1100 {
1101     IDEState *ide_state;
1102     uint32_t opts;
1103     uint64_t tbl_addr;
1104     AHCICmdHdr *cmd;
1105     uint8_t *cmd_fis;
1106     target_phys_addr_t cmd_len;
1107 
1108     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1109         /* Engine currently busy, try again later */
1110         DPRINTF(port, "engine busy\n");
1111         return -1;
1112     }
1113 
1114     cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];
1115 
1116     if (!s->dev[port].lst) {
1117         DPRINTF(port, "error: lst not given but cmd handled");
1118         return -1;
1119     }
1120 
1121     /* remember current slot handle for later */
1122     s->dev[port].cur_cmd = cmd;
1123 
1124     opts = le32_to_cpu(cmd->opts);
1125     tbl_addr = le64_to_cpu(cmd->tbl_addr);
1126 
1127     cmd_len = 0x80;
1128     cmd_fis = cpu_physical_memory_map(tbl_addr, &cmd_len, 1);
1129 
1130     if (!cmd_fis) {
1131         DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
1132         return -1;
1133     }
1134 
1135     /* The device we are working for */
1136     ide_state = &s->dev[port].port.ifs[0];
1137 
1138     if (!ide_state->bs) {
1139         DPRINTF(port, "error: guest accessed unused port");
1140         goto out;
1141     }
1142 
1143     debug_print_fis(cmd_fis, 0x90);
1144     //debug_print_fis(cmd_fis, (opts & AHCI_CMD_HDR_CMD_FIS_LEN) * 4);
1145 
1146     switch (cmd_fis[0]) {
1147         case SATA_FIS_TYPE_REGISTER_H2D:
1148             break;
1149         default:
1150             DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
1151                           "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
1152                           cmd_fis[2]);
1153             goto out;
1154             break;
1155     }
1156 
1157     switch (cmd_fis[1]) {
1158         case SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER:
1159             break;
1160         case 0:
1161             break;
1162         default:
1163             DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "
1164                           "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],
1165                           cmd_fis[2]);
1166             goto out;
1167             break;
1168     }
1169 
1170     switch (s->dev[port].port_state) {
1171         case STATE_RUN:
1172             if (cmd_fis[15] & ATA_SRST) {
1173                 s->dev[port].port_state = STATE_RESET;
1174             }
1175             break;
1176         case STATE_RESET:
1177             if (!(cmd_fis[15] & ATA_SRST)) {
1178                 ahci_reset_port(s, port);
1179             }
1180             break;
1181     }
1182 
1183     if (cmd_fis[1] == SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER) {
1184 
1185         /* Check for NCQ command */
1186         if ((cmd_fis[2] == READ_FPDMA_QUEUED) ||
1187             (cmd_fis[2] == WRITE_FPDMA_QUEUED)) {
1188             process_ncq_command(s, port, cmd_fis, slot);
1189             goto out;
1190         }
1191 
1192         /* Decompose the FIS  */
1193         ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);
1194         ide_state->feature = cmd_fis[3];
1195         if (!ide_state->nsector) {
1196             ide_state->nsector = 256;
1197         }
1198 
1199         if (ide_state->drive_kind != IDE_CD) {
1200             ide_set_sector(ide_state, (cmd_fis[6] << 16) | (cmd_fis[5] << 8) |
1201                            cmd_fis[4]);
1202         }
1203 
1204         /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command
1205          * table to ide_state->io_buffer
1206          */
1207         if (opts & AHCI_CMD_ATAPI) {
1208             memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);
1209             ide_state->lcyl = 0x14;
1210             ide_state->hcyl = 0xeb;
1211             debug_print_fis(ide_state->io_buffer, 0x10);
1212             ide_state->feature = IDE_FEATURE_DMA;
1213             s->dev[port].done_atapi_packet = 0;
1214             /* XXX send PIO setup FIS */
1215         }
1216 
1217         ide_state->error = 0;
1218 
1219         /* Reset transferred byte counter */
1220         cmd->status = 0;
1221 
1222         /* We're ready to process the command in FIS byte 2. */
1223         ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);
1224 
1225         if (s->dev[port].port.ifs[0].status & READY_STAT) {
1226             ahci_write_fis_d2h(&s->dev[port], cmd_fis);
1227         }
1228     }
1229 
1230 out:
1231     cpu_physical_memory_unmap(cmd_fis, 1, cmd_len, cmd_len);
1232 
1233     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
1234         /* async command, complete later */
1235         s->dev[port].busy_slot = slot;
1236         return -1;
1237     }
1238 
1239     /* done handling the command */
1240     return 0;
1241 }
1242 
1243 /* DMA dev <-> ram */
1244 static int ahci_start_transfer(IDEDMA *dma)
1245 {
1246     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1247     IDEState *s = &ad->port.ifs[0];
1248     uint32_t size = (uint32_t)(s->data_end - s->data_ptr);
1249     /* write == ram -> device */
1250     uint32_t opts = le32_to_cpu(ad->cur_cmd->opts);
1251     int is_write = opts & AHCI_CMD_WRITE;
1252     int is_atapi = opts & AHCI_CMD_ATAPI;
1253     int has_sglist = 0;
1254 
1255     if (is_atapi && !ad->done_atapi_packet) {
1256         /* already prepopulated iobuffer */
1257         ad->done_atapi_packet = 1;
1258         goto out;
1259     }
1260 
1261     if (!ahci_populate_sglist(ad, &s->sg)) {
1262         has_sglist = 1;
1263     }
1264 
1265     DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",
1266             is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",
1267             has_sglist ? "" : "o");
1268 
1269     if (is_write && has_sglist && (s->data_ptr < s->data_end)) {
1270         read_from_sglist(s->data_ptr, size, &s->sg);
1271     }
1272 
1273     if (!is_write && has_sglist && (s->data_ptr < s->data_end)) {
1274         write_to_sglist(s->data_ptr, size, &s->sg);
1275     }
1276 
1277     /* update number of transferred bytes */
1278     ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + size);
1279 
1280 out:
1281     /* declare that we processed everything */
1282     s->data_ptr = s->data_end;
1283 
1284     if (has_sglist) {
1285         qemu_sglist_destroy(&s->sg);
1286     }
1287 
1288     s->end_transfer_func(s);
1289 
1290     if (!(s->status & DRQ_STAT)) {
1291         /* done with DMA */
1292         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_DSS);
1293     }
1294 
1295     return 0;
1296 }
1297 
1298 static void ahci_start_dma(IDEDMA *dma, IDEState *s,
1299                            BlockDriverCompletionFunc *dma_cb)
1300 {
1301     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1302 
1303     DPRINTF(ad->port_no, "\n");
1304     ad->dma_cb = dma_cb;
1305     ad->dma_status |= BM_STATUS_DMAING;
1306     dma_cb(s, 0);
1307 }
1308 
1309 static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write)
1310 {
1311     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1312     IDEState *s = &ad->port.ifs[0];
1313     int i;
1314 
1315     ahci_populate_sglist(ad, &s->sg);
1316 
1317     s->io_buffer_size = 0;
1318     for (i = 0; i < s->sg.nsg; i++) {
1319         s->io_buffer_size += s->sg.sg[i].len;
1320     }
1321 
1322     DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
1323     return s->io_buffer_size != 0;
1324 }
1325 
1326 static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
1327 {
1328     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1329     IDEState *s = &ad->port.ifs[0];
1330     uint8_t *p = s->io_buffer + s->io_buffer_index;
1331     int l = s->io_buffer_size - s->io_buffer_index;
1332 
1333     if (ahci_populate_sglist(ad, &s->sg)) {
1334         return 0;
1335     }
1336 
1337     if (is_write) {
1338         write_to_sglist(p, l, &s->sg);
1339     } else {
1340         read_from_sglist(p, l, &s->sg);
1341     }
1342 
1343     /* update number of transferred bytes */
1344     ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + l);
1345     s->io_buffer_index += l;
1346 
1347     DPRINTF(ad->port_no, "len=%#x\n", l);
1348 
1349     return 1;
1350 }
1351 
1352 static int ahci_dma_set_unit(IDEDMA *dma, int unit)
1353 {
1354     /* only a single unit per link */
1355     return 0;
1356 }
1357 
1358 static int ahci_dma_add_status(IDEDMA *dma, int status)
1359 {
1360     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1361     ad->dma_status |= status;
1362     DPRINTF(ad->port_no, "set status: %x\n", status);
1363 
1364     if (status & BM_STATUS_INT) {
1365         ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_DSS);
1366     }
1367 
1368     return 0;
1369 }
1370 
1371 static int ahci_dma_set_inactive(IDEDMA *dma)
1372 {
1373     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
1374 
1375     DPRINTF(ad->port_no, "dma done\n");
1376 
1377     /* update d2h status */
1378     ahci_write_fis_d2h(ad, NULL);
1379 
1380     ad->dma_cb = NULL;
1381 
1382     /* maybe we still have something to process, check later */
1383     ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad);
1384     qemu_bh_schedule(ad->check_bh);
1385 
1386     return 0;
1387 }
1388 
1389 static void ahci_irq_set(void *opaque, int n, int level)
1390 {
1391 }
1392 
1393 static void ahci_dma_restart_cb(void *opaque, int running, int reason)
1394 {
1395 }
1396 
1397 static int ahci_dma_reset(IDEDMA *dma)
1398 {
1399     return 0;
1400 }
1401 
1402 static const IDEDMAOps ahci_dma_ops = {
1403     .start_dma = ahci_start_dma,
1404     .start_transfer = ahci_start_transfer,
1405     .prepare_buf = ahci_dma_prepare_buf,
1406     .rw_buf = ahci_dma_rw_buf,
1407     .set_unit = ahci_dma_set_unit,
1408     .add_status = ahci_dma_add_status,
1409     .set_inactive = ahci_dma_set_inactive,
1410     .restart_cb = ahci_dma_restart_cb,
1411     .reset = ahci_dma_reset,
1412 };
1413 
1414 static void ahci_init(AHCIState *s, DeviceState *qdev)
1415 {
1416     qemu_irq *irqs;
1417     int i;
1418 
1419     ahci_reg_init(s);
1420     s->mem = cpu_register_io_memory(ahci_readfn, ahci_writefn, s,
1421                                     DEVICE_LITTLE_ENDIAN);
1422     irqs = qemu_allocate_irqs(ahci_irq_set, s, SATA_PORTS);
1423 
1424     for (i = 0; i < SATA_PORTS; i++) {
1425         AHCIDevice *ad = &s->dev[i];
1426 
1427         ide_bus_new(&ad->port, qdev, i);
1428         ide_init2(&ad->port, irqs[i]);
1429 
1430         ad->hba = s;
1431         ad->port_no = i;
1432         ad->port.dma = &ad->dma;
1433         ad->port.dma->ops = &ahci_dma_ops;
1434         ad->port_regs.cmd = PORT_CMD_SPIN_UP | PORT_CMD_POWER_ON;
1435     }
1436 }
1437 
1438 static void ahci_pci_map(PCIDevice *pci_dev, int region_num,
1439         pcibus_t addr, pcibus_t size, int type)
1440 {
1441     struct AHCIPCIState *d = (struct AHCIPCIState *)pci_dev;
1442     AHCIState *s = &d->ahci;
1443 
1444     cpu_register_physical_memory(addr, size, s->mem);
1445 }
1446 
1447 static void ahci_reset(void *opaque)
1448 {
1449     struct AHCIPCIState *d = opaque;
1450     int i;
1451 
1452     for (i = 0; i < SATA_PORTS; i++) {
1453         ahci_reset_port(&d->ahci, i);
1454     }
1455 }
1456 
1457 static int pci_ahci_init(PCIDevice *dev)
1458 {
1459     struct AHCIPCIState *d;
1460     d = DO_UPCAST(struct AHCIPCIState, card, dev);
1461 
1462     pci_config_set_vendor_id(d->card.config, PCI_VENDOR_ID_INTEL);
1463     pci_config_set_device_id(d->card.config, PCI_DEVICE_ID_INTEL_82801IR);
1464 
1465     pci_config_set_class(d->card.config, PCI_CLASS_STORAGE_SATA);
1466     pci_config_set_revision(d->card.config, 0x02);
1467     pci_config_set_prog_interface(d->card.config, AHCI_PROGMODE_MAJOR_REV_1);
1468 
1469     d->card.config[PCI_CACHE_LINE_SIZE] = 0x08;  /* Cache line size */
1470     d->card.config[PCI_LATENCY_TIMER]   = 0x00;  /* Latency timer */
1471     pci_config_set_interrupt_pin(d->card.config, 1);
1472 
1473     /* XXX Software should program this register */
1474     d->card.config[0x90]   = 1 << 6; /* Address Map Register - AHCI mode */
1475 
1476     qemu_register_reset(ahci_reset, d);
1477 
1478     /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */
1479     pci_register_bar(&d->card, 5, 0x1000, PCI_BASE_ADDRESS_SPACE_MEMORY,
1480                      ahci_pci_map);
1481 
1482     msi_init(dev, 0x50, 1, true, false);
1483 
1484     ahci_init(&d->ahci, &dev->qdev);
1485     d->ahci.irq = d->card.irq[0];
1486 
1487     return 0;
1488 }
1489 
1490 static int pci_ahci_uninit(PCIDevice *dev)
1491 {
1492     struct AHCIPCIState *d;
1493     d = DO_UPCAST(struct AHCIPCIState, card, dev);
1494 
1495     if (msi_enabled(dev)) {
1496         msi_uninit(dev);
1497     }
1498 
1499     qemu_unregister_reset(ahci_reset, d);
1500 
1501     return 0;
1502 }
1503 
1504 static void pci_ahci_write_config(PCIDevice *pci, uint32_t addr,
1505                                   uint32_t val, int len)
1506 {
1507     pci_default_write_config(pci, addr, val, len);
1508     msi_write_config(pci, addr, val, len);
1509 }
1510 
1511 static PCIDeviceInfo ahci_info = {
1512     .qdev.name  = "ahci",
1513     .qdev.size  = sizeof(AHCIPCIState),
1514     .init       = pci_ahci_init,
1515     .exit       = pci_ahci_uninit,
1516     .config_write = pci_ahci_write_config,
1517 };
1518 
1519 static void ahci_pci_register_devices(void)
1520 {
1521     pci_qdev_register(&ahci_info);
1522 }
1523 
1524 device_init(ahci_pci_register_devices)
1525