]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/pci_ahci.c
Merge branch 'releng/11.1' into releng-CDN/11.1
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / pci_ahci.c
1 /*-
2  * Copyright (c) 2013  Zhixiang Yu <zcore@freebsd.org>
3  * Copyright (c) 2015-2016 Alexander Motin <mav@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/linker_set.h>
35 #include <sys/stat.h>
36 #include <sys/uio.h>
37 #include <sys/ioctl.h>
38 #include <sys/disk.h>
39 #include <sys/ata.h>
40 #include <sys/endian.h>
41
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <string.h>
48 #include <strings.h>
49 #include <unistd.h>
50 #include <assert.h>
51 #include <pthread.h>
52 #include <pthread_np.h>
53 #include <inttypes.h>
54 #include <md5.h>
55
56 #include "bhyverun.h"
57 #include "pci_emul.h"
58 #include "ahci.h"
59 #include "block_if.h"
60
61 #define DEF_PORTS       6       /* Intel ICH8 AHCI supports 6 ports */
62 #define MAX_PORTS       32      /* AHCI supports 32 ports */
63
64 #define PxSIG_ATA       0x00000101 /* ATA drive */
65 #define PxSIG_ATAPI     0xeb140101 /* ATAPI drive */
66
67 enum sata_fis_type {
68         FIS_TYPE_REGH2D         = 0x27, /* Register FIS - host to device */
69         FIS_TYPE_REGD2H         = 0x34, /* Register FIS - device to host */
70         FIS_TYPE_DMAACT         = 0x39, /* DMA activate FIS - device to host */
71         FIS_TYPE_DMASETUP       = 0x41, /* DMA setup FIS - bidirectional */
72         FIS_TYPE_DATA           = 0x46, /* Data FIS - bidirectional */
73         FIS_TYPE_BIST           = 0x58, /* BIST activate FIS - bidirectional */
74         FIS_TYPE_PIOSETUP       = 0x5F, /* PIO setup FIS - device to host */
75         FIS_TYPE_SETDEVBITS     = 0xA1, /* Set dev bits FIS - device to host */
76 };
77
78 /*
79  * SCSI opcodes
80  */
81 #define TEST_UNIT_READY         0x00
82 #define REQUEST_SENSE           0x03
83 #define INQUIRY                 0x12
84 #define START_STOP_UNIT         0x1B
85 #define PREVENT_ALLOW           0x1E
86 #define READ_CAPACITY           0x25
87 #define READ_10                 0x28
88 #define POSITION_TO_ELEMENT     0x2B
89 #define READ_TOC                0x43
90 #define GET_EVENT_STATUS_NOTIFICATION 0x4A
91 #define MODE_SENSE_10           0x5A
92 #define REPORT_LUNS             0xA0
93 #define READ_12                 0xA8
94 #define READ_CD                 0xBE
95
96 /*
97  * SCSI mode page codes
98  */
99 #define MODEPAGE_RW_ERROR_RECOVERY      0x01
100 #define MODEPAGE_CD_CAPABILITIES        0x2A
101
102 /*
103  * ATA commands
104  */
105 #define ATA_SF_ENAB_SATA_SF             0x10
106 #define         ATA_SATA_SF_AN          0x05
107 #define ATA_SF_DIS_SATA_SF              0x90
108
109 /*
110  * Debug printf
111  */
112 #ifdef AHCI_DEBUG
113 static FILE *dbg;
114 #define DPRINTF(format, arg...) do{fprintf(dbg, format, ##arg);fflush(dbg);}while(0)
115 #else
116 #define DPRINTF(format, arg...)
117 #endif
118 #define WPRINTF(format, arg...) printf(format, ##arg)
119
120 struct ahci_ioreq {
121         struct blockif_req io_req;
122         struct ahci_port *io_pr;
123         STAILQ_ENTRY(ahci_ioreq) io_flist;
124         TAILQ_ENTRY(ahci_ioreq) io_blist;
125         uint8_t *cfis;
126         uint32_t len;
127         uint32_t done;
128         int slot;
129         int more;
130 };
131
132 struct ahci_port {
133         struct blockif_ctxt *bctx;
134         struct pci_ahci_softc *pr_sc;
135         uint8_t *cmd_lst;
136         uint8_t *rfis;
137         char ident[20 + 1];
138         int port;
139         int atapi;
140         int reset;
141         int waitforclear;
142         int mult_sectors;
143         uint8_t xfermode;
144         uint8_t err_cfis[20];
145         uint8_t sense_key;
146         uint8_t asc;
147         u_int ccs;
148         uint32_t pending;
149
150         uint32_t clb;
151         uint32_t clbu;
152         uint32_t fb;
153         uint32_t fbu;
154         uint32_t is;
155         uint32_t ie;
156         uint32_t cmd;
157         uint32_t unused0;
158         uint32_t tfd;
159         uint32_t sig;
160         uint32_t ssts;
161         uint32_t sctl;
162         uint32_t serr;
163         uint32_t sact;
164         uint32_t ci;
165         uint32_t sntf;
166         uint32_t fbs;
167
168         /*
169          * i/o request info
170          */
171         struct ahci_ioreq *ioreq;
172         int ioqsz;
173         STAILQ_HEAD(ahci_fhead, ahci_ioreq) iofhd;
174         TAILQ_HEAD(ahci_bhead, ahci_ioreq) iobhd;
175 };
176
177 struct ahci_cmd_hdr {
178         uint16_t flags;
179         uint16_t prdtl;
180         uint32_t prdbc;
181         uint64_t ctba;
182         uint32_t reserved[4];
183 };
184
185 struct ahci_prdt_entry {
186         uint64_t dba;
187         uint32_t reserved;
188 #define DBCMASK         0x3fffff
189         uint32_t dbc;
190 };
191
192 struct pci_ahci_softc {
193         struct pci_devinst *asc_pi;
194         pthread_mutex_t mtx;
195         int ports;
196         uint32_t cap;
197         uint32_t ghc;
198         uint32_t is;
199         uint32_t pi;
200         uint32_t vs;
201         uint32_t ccc_ctl;
202         uint32_t ccc_pts;
203         uint32_t em_loc;
204         uint32_t em_ctl;
205         uint32_t cap2;
206         uint32_t bohc;
207         uint32_t lintr;
208         struct ahci_port port[MAX_PORTS];
209 };
210 #define ahci_ctx(sc)    ((sc)->asc_pi->pi_vmctx)
211
212 static void ahci_handle_port(struct ahci_port *p);
213
214 static inline void lba_to_msf(uint8_t *buf, int lba)
215 {
216         lba += 150;
217         buf[0] = (lba / 75) / 60;
218         buf[1] = (lba / 75) % 60;
219         buf[2] = lba % 75;
220 }
221
222 /*
223  * Generate HBA interrupts on global IS register write.
224  */
225 static void
226 ahci_generate_intr(struct pci_ahci_softc *sc, uint32_t mask)
227 {
228         struct pci_devinst *pi = sc->asc_pi;
229         struct ahci_port *p;
230         int i, nmsg;
231         uint32_t mmask;
232
233         /* Update global IS from PxIS/PxIE. */
234         for (i = 0; i < sc->ports; i++) {
235                 p = &sc->port[i];
236                 if (p->is & p->ie)
237                         sc->is |= (1 << i);
238         }
239         DPRINTF("%s(%08x) %08x\n", __func__, mask, sc->is);
240
241         /* If there is nothing enabled -- clear legacy interrupt and exit. */
242         if (sc->is == 0 || (sc->ghc & AHCI_GHC_IE) == 0) {
243                 if (sc->lintr) {
244                         pci_lintr_deassert(pi);
245                         sc->lintr = 0;
246                 }
247                 return;
248         }
249
250         /* If there is anything and no MSI -- assert legacy interrupt. */
251         nmsg = pci_msi_maxmsgnum(pi);
252         if (nmsg == 0) {
253                 if (!sc->lintr) {
254                         sc->lintr = 1;
255                         pci_lintr_assert(pi);
256                 }
257                 return;
258         }
259
260         /* Assert respective MSIs for ports that were touched. */
261         for (i = 0; i < nmsg; i++) {
262                 if (sc->ports <= nmsg || i < nmsg - 1)
263                         mmask = 1 << i;
264                 else
265                         mmask = 0xffffffff << i;
266                 if (sc->is & mask && mmask & mask)
267                         pci_generate_msi(pi, i);
268         }
269 }
270
271 /*
272  * Generate HBA interrupt on specific port event.
273  */
274 static void
275 ahci_port_intr(struct ahci_port *p)
276 {
277         struct pci_ahci_softc *sc = p->pr_sc;
278         struct pci_devinst *pi = sc->asc_pi;
279         int nmsg;
280
281         DPRINTF("%s(%d) %08x/%08x %08x\n", __func__,
282             p->port, p->is, p->ie, sc->is);
283
284         /* If there is nothing enabled -- we are done. */
285         if ((p->is & p->ie) == 0)
286                 return;
287
288         /* In case of non-shared MSI always generate interrupt. */
289         nmsg = pci_msi_maxmsgnum(pi);
290         if (sc->ports <= nmsg || p->port < nmsg - 1) {
291                 sc->is |= (1 << p->port);
292                 if ((sc->ghc & AHCI_GHC_IE) == 0)
293                         return;
294                 pci_generate_msi(pi, p->port);
295                 return;
296         }
297
298         /* If IS for this port is already set -- do nothing. */
299         if (sc->is & (1 << p->port))
300                 return;
301
302         sc->is |= (1 << p->port);
303
304         /* If interrupts are enabled -- generate one. */
305         if ((sc->ghc & AHCI_GHC_IE) == 0)
306                 return;
307         if (nmsg > 0) {
308                 pci_generate_msi(pi, nmsg - 1);
309         } else if (!sc->lintr) {
310                 sc->lintr = 1;
311                 pci_lintr_assert(pi);
312         }
313 }
314
315 static void
316 ahci_write_fis(struct ahci_port *p, enum sata_fis_type ft, uint8_t *fis)
317 {
318         int offset, len, irq;
319
320         if (p->rfis == NULL || !(p->cmd & AHCI_P_CMD_FRE))
321                 return;
322
323         switch (ft) {
324         case FIS_TYPE_REGD2H:
325                 offset = 0x40;
326                 len = 20;
327                 irq = (fis[1] & (1 << 6)) ? AHCI_P_IX_DHR : 0;
328                 break;
329         case FIS_TYPE_SETDEVBITS:
330                 offset = 0x58;
331                 len = 8;
332                 irq = (fis[1] & (1 << 6)) ? AHCI_P_IX_SDB : 0;
333                 break;
334         case FIS_TYPE_PIOSETUP:
335                 offset = 0x20;
336                 len = 20;
337                 irq = (fis[1] & (1 << 6)) ? AHCI_P_IX_PS : 0;
338                 break;
339         default:
340                 WPRINTF("unsupported fis type %d\n", ft);
341                 return;
342         }
343         if (fis[2] & ATA_S_ERROR) {
344                 p->waitforclear = 1;
345                 irq |= AHCI_P_IX_TFE;
346         }
347         memcpy(p->rfis + offset, fis, len);
348         if (irq) {
349                 if (~p->is & irq) {
350                         p->is |= irq;
351                         ahci_port_intr(p);
352                 }
353         }
354 }
355
356 static void
357 ahci_write_fis_piosetup(struct ahci_port *p)
358 {
359         uint8_t fis[20];
360
361         memset(fis, 0, sizeof(fis));
362         fis[0] = FIS_TYPE_PIOSETUP;
363         ahci_write_fis(p, FIS_TYPE_PIOSETUP, fis);
364 }
365
366 static void
367 ahci_write_fis_sdb(struct ahci_port *p, int slot, uint8_t *cfis, uint32_t tfd)
368 {
369         uint8_t fis[8];
370         uint8_t error;
371
372         error = (tfd >> 8) & 0xff;
373         tfd &= 0x77;
374         memset(fis, 0, sizeof(fis));
375         fis[0] = FIS_TYPE_SETDEVBITS;
376         fis[1] = (1 << 6);
377         fis[2] = tfd;
378         fis[3] = error;
379         if (fis[2] & ATA_S_ERROR) {
380                 p->err_cfis[0] = slot;
381                 p->err_cfis[2] = tfd;
382                 p->err_cfis[3] = error;
383                 memcpy(&p->err_cfis[4], cfis + 4, 16);
384         } else {
385                 *(uint32_t *)(fis + 4) = (1 << slot);
386                 p->sact &= ~(1 << slot);
387         }
388         p->tfd &= ~0x77;
389         p->tfd |= tfd;
390         ahci_write_fis(p, FIS_TYPE_SETDEVBITS, fis);
391 }
392
393 static void
394 ahci_write_fis_d2h(struct ahci_port *p, int slot, uint8_t *cfis, uint32_t tfd)
395 {
396         uint8_t fis[20];
397         uint8_t error;
398
399         error = (tfd >> 8) & 0xff;
400         memset(fis, 0, sizeof(fis));
401         fis[0] = FIS_TYPE_REGD2H;
402         fis[1] = (1 << 6);
403         fis[2] = tfd & 0xff;
404         fis[3] = error;
405         fis[4] = cfis[4];
406         fis[5] = cfis[5];
407         fis[6] = cfis[6];
408         fis[7] = cfis[7];
409         fis[8] = cfis[8];
410         fis[9] = cfis[9];
411         fis[10] = cfis[10];
412         fis[11] = cfis[11];
413         fis[12] = cfis[12];
414         fis[13] = cfis[13];
415         if (fis[2] & ATA_S_ERROR) {
416                 p->err_cfis[0] = 0x80;
417                 p->err_cfis[2] = tfd & 0xff;
418                 p->err_cfis[3] = error;
419                 memcpy(&p->err_cfis[4], cfis + 4, 16);
420         } else
421                 p->ci &= ~(1 << slot);
422         p->tfd = tfd;
423         ahci_write_fis(p, FIS_TYPE_REGD2H, fis);
424 }
425
426 static void
427 ahci_write_fis_d2h_ncq(struct ahci_port *p, int slot)
428 {
429         uint8_t fis[20];
430
431         p->tfd = ATA_S_READY | ATA_S_DSC;
432         memset(fis, 0, sizeof(fis));
433         fis[0] = FIS_TYPE_REGD2H;
434         fis[1] = 0;                     /* No interrupt */
435         fis[2] = p->tfd;                /* Status */
436         fis[3] = 0;                     /* No error */
437         p->ci &= ~(1 << slot);
438         ahci_write_fis(p, FIS_TYPE_REGD2H, fis);
439 }
440
441 static void
442 ahci_write_reset_fis_d2h(struct ahci_port *p)
443 {
444         uint8_t fis[20];
445
446         memset(fis, 0, sizeof(fis));
447         fis[0] = FIS_TYPE_REGD2H;
448         fis[3] = 1;
449         fis[4] = 1;
450         if (p->atapi) {
451                 fis[5] = 0x14;
452                 fis[6] = 0xeb;
453         }
454         fis[12] = 1;
455         ahci_write_fis(p, FIS_TYPE_REGD2H, fis);
456 }
457
458 static void
459 ahci_check_stopped(struct ahci_port *p)
460 {
461         /*
462          * If we are no longer processing the command list and nothing
463          * is in-flight, clear the running bit, the current command
464          * slot, the command issue and active bits.
465          */
466         if (!(p->cmd & AHCI_P_CMD_ST)) {
467                 if (p->pending == 0) {
468                         p->ccs = 0;
469                         p->cmd &= ~(AHCI_P_CMD_CR | AHCI_P_CMD_CCS_MASK);
470                         p->ci = 0;
471                         p->sact = 0;
472                         p->waitforclear = 0;
473                 }
474         }
475 }
476
477 static void
478 ahci_port_stop(struct ahci_port *p)
479 {
480         struct ahci_ioreq *aior;
481         uint8_t *cfis;
482         int slot;
483         int error;
484
485         assert(pthread_mutex_isowned_np(&p->pr_sc->mtx));
486
487         TAILQ_FOREACH(aior, &p->iobhd, io_blist) {
488                 /*
489                  * Try to cancel the outstanding blockif request.
490                  */
491                 error = blockif_cancel(p->bctx, &aior->io_req);
492                 if (error != 0)
493                         continue;
494
495                 slot = aior->slot;
496                 cfis = aior->cfis;
497                 if (cfis[2] == ATA_WRITE_FPDMA_QUEUED ||
498                     cfis[2] == ATA_READ_FPDMA_QUEUED ||
499                     cfis[2] == ATA_SEND_FPDMA_QUEUED)
500                         p->sact &= ~(1 << slot);        /* NCQ */
501                 else
502                         p->ci &= ~(1 << slot);
503
504                 /*
505                  * This command is now done.
506                  */
507                 p->pending &= ~(1 << slot);
508
509                 /*
510                  * Delete the blockif request from the busy list
511                  */
512                 TAILQ_REMOVE(&p->iobhd, aior, io_blist);
513
514                 /*
515                  * Move the blockif request back to the free list
516                  */
517                 STAILQ_INSERT_TAIL(&p->iofhd, aior, io_flist);
518         }
519
520         ahci_check_stopped(p);
521 }
522
523 static void
524 ahci_port_reset(struct ahci_port *pr)
525 {
526         pr->serr = 0;
527         pr->sact = 0;
528         pr->xfermode = ATA_UDMA6;
529         pr->mult_sectors = 128;
530
531         if (!pr->bctx) {
532                 pr->ssts = ATA_SS_DET_NO_DEVICE;
533                 pr->sig = 0xFFFFFFFF;
534                 pr->tfd = 0x7F;
535                 return;
536         }
537         pr->ssts = ATA_SS_DET_PHY_ONLINE | ATA_SS_IPM_ACTIVE;
538         if (pr->sctl & ATA_SC_SPD_MASK)
539                 pr->ssts |= (pr->sctl & ATA_SC_SPD_MASK);
540         else
541                 pr->ssts |= ATA_SS_SPD_GEN3;
542         pr->tfd = (1 << 8) | ATA_S_DSC | ATA_S_DMA;
543         if (!pr->atapi) {
544                 pr->sig = PxSIG_ATA;
545                 pr->tfd |= ATA_S_READY;
546         } else
547                 pr->sig = PxSIG_ATAPI;
548         ahci_write_reset_fis_d2h(pr);
549 }
550
551 static void
552 ahci_reset(struct pci_ahci_softc *sc)
553 {
554         int i;
555
556         sc->ghc = AHCI_GHC_AE;
557         sc->is = 0;
558
559         if (sc->lintr) {
560                 pci_lintr_deassert(sc->asc_pi);
561                 sc->lintr = 0;
562         }
563
564         for (i = 0; i < sc->ports; i++) {
565                 sc->port[i].ie = 0;
566                 sc->port[i].is = 0;
567                 sc->port[i].cmd = (AHCI_P_CMD_SUD | AHCI_P_CMD_POD);
568                 if (sc->port[i].bctx)
569                         sc->port[i].cmd |= AHCI_P_CMD_CPS;
570                 sc->port[i].sctl = 0;
571                 ahci_port_reset(&sc->port[i]);
572         }
573 }
574
575 static void
576 ata_string(uint8_t *dest, const char *src, int len)
577 {
578         int i;
579
580         for (i = 0; i < len; i++) {
581                 if (*src)
582                         dest[i ^ 1] = *src++;
583                 else
584                         dest[i ^ 1] = ' ';
585         }
586 }
587
588 static void
589 atapi_string(uint8_t *dest, const char *src, int len)
590 {
591         int i;
592
593         for (i = 0; i < len; i++) {
594                 if (*src)
595                         dest[i] = *src++;
596                 else
597                         dest[i] = ' ';
598         }
599 }
600
601 /*
602  * Build up the iovec based on the PRDT, 'done' and 'len'.
603  */
604 static void
605 ahci_build_iov(struct ahci_port *p, struct ahci_ioreq *aior,
606     struct ahci_prdt_entry *prdt, uint16_t prdtl)
607 {
608         struct blockif_req *breq = &aior->io_req;
609         int i, j, skip, todo, left, extra;
610         uint32_t dbcsz;
611
612         /* Copy part of PRDT between 'done' and 'len' bytes into the iov. */
613         skip = aior->done;
614         left = aior->len - aior->done;
615         todo = 0;
616         for (i = 0, j = 0; i < prdtl && j < BLOCKIF_IOV_MAX && left > 0;
617             i++, prdt++) {
618                 dbcsz = (prdt->dbc & DBCMASK) + 1;
619                 /* Skip already done part of the PRDT */
620                 if (dbcsz <= skip) {
621                         skip -= dbcsz;
622                         continue;
623                 }
624                 dbcsz -= skip;
625                 if (dbcsz > left)
626                         dbcsz = left;
627                 breq->br_iov[j].iov_base = paddr_guest2host(ahci_ctx(p->pr_sc),
628                     prdt->dba + skip, dbcsz);
629                 breq->br_iov[j].iov_len = dbcsz;
630                 todo += dbcsz;
631                 left -= dbcsz;
632                 skip = 0;
633                 j++;
634         }
635
636         /* If we got limited by IOV length, round I/O down to sector size. */
637         if (j == BLOCKIF_IOV_MAX) {
638                 extra = todo % blockif_sectsz(p->bctx);
639                 todo -= extra;
640                 assert(todo > 0);
641                 while (extra > 0) {
642                         if (breq->br_iov[j - 1].iov_len > extra) {
643                                 breq->br_iov[j - 1].iov_len -= extra;
644                                 break;
645                         }
646                         extra -= breq->br_iov[j - 1].iov_len;
647                         j--;
648                 }
649         }
650
651         breq->br_iovcnt = j;
652         breq->br_resid = todo;
653         aior->done += todo;
654         aior->more = (aior->done < aior->len && i < prdtl);
655 }
656
657 static void
658 ahci_handle_rw(struct ahci_port *p, int slot, uint8_t *cfis, uint32_t done)
659 {
660         struct ahci_ioreq *aior;
661         struct blockif_req *breq;
662         struct ahci_prdt_entry *prdt;
663         struct ahci_cmd_hdr *hdr;
664         uint64_t lba;
665         uint32_t len;
666         int err, first, ncq, readop;
667
668         prdt = (struct ahci_prdt_entry *)(cfis + 0x80);
669         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
670         ncq = 0;
671         readop = 1;
672         first = (done == 0);
673
674         if (cfis[2] == ATA_WRITE || cfis[2] == ATA_WRITE48 ||
675             cfis[2] == ATA_WRITE_MUL || cfis[2] == ATA_WRITE_MUL48 ||
676             cfis[2] == ATA_WRITE_DMA || cfis[2] == ATA_WRITE_DMA48 ||
677             cfis[2] == ATA_WRITE_FPDMA_QUEUED)
678                 readop = 0;
679
680         if (cfis[2] == ATA_WRITE_FPDMA_QUEUED ||
681             cfis[2] == ATA_READ_FPDMA_QUEUED) {
682                 lba = ((uint64_t)cfis[10] << 40) |
683                         ((uint64_t)cfis[9] << 32) |
684                         ((uint64_t)cfis[8] << 24) |
685                         ((uint64_t)cfis[6] << 16) |
686                         ((uint64_t)cfis[5] << 8) |
687                         cfis[4];
688                 len = cfis[11] << 8 | cfis[3];
689                 if (!len)
690                         len = 65536;
691                 ncq = 1;
692         } else if (cfis[2] == ATA_READ48 || cfis[2] == ATA_WRITE48 ||
693             cfis[2] == ATA_READ_MUL48 || cfis[2] == ATA_WRITE_MUL48 ||
694             cfis[2] == ATA_READ_DMA48 || cfis[2] == ATA_WRITE_DMA48) {
695                 lba = ((uint64_t)cfis[10] << 40) |
696                         ((uint64_t)cfis[9] << 32) |
697                         ((uint64_t)cfis[8] << 24) |
698                         ((uint64_t)cfis[6] << 16) |
699                         ((uint64_t)cfis[5] << 8) |
700                         cfis[4];
701                 len = cfis[13] << 8 | cfis[12];
702                 if (!len)
703                         len = 65536;
704         } else {
705                 lba = ((cfis[7] & 0xf) << 24) | (cfis[6] << 16) |
706                         (cfis[5] << 8) | cfis[4];
707                 len = cfis[12];
708                 if (!len)
709                         len = 256;
710         }
711         lba *= blockif_sectsz(p->bctx);
712         len *= blockif_sectsz(p->bctx);
713
714         /* Pull request off free list */
715         aior = STAILQ_FIRST(&p->iofhd);
716         assert(aior != NULL);
717         STAILQ_REMOVE_HEAD(&p->iofhd, io_flist);
718
719         aior->cfis = cfis;
720         aior->slot = slot;
721         aior->len = len;
722         aior->done = done;
723         breq = &aior->io_req;
724         breq->br_offset = lba + done;
725         ahci_build_iov(p, aior, prdt, hdr->prdtl);
726
727         /* Mark this command in-flight. */
728         p->pending |= 1 << slot;
729
730         /* Stuff request onto busy list. */
731         TAILQ_INSERT_HEAD(&p->iobhd, aior, io_blist);
732
733         if (ncq && first)
734                 ahci_write_fis_d2h_ncq(p, slot);
735
736         if (readop)
737                 err = blockif_read(p->bctx, breq);
738         else
739                 err = blockif_write(p->bctx, breq);
740         assert(err == 0);
741 }
742
743 static void
744 ahci_handle_flush(struct ahci_port *p, int slot, uint8_t *cfis)
745 {
746         struct ahci_ioreq *aior;
747         struct blockif_req *breq;
748         int err;
749
750         /*
751          * Pull request off free list
752          */
753         aior = STAILQ_FIRST(&p->iofhd);
754         assert(aior != NULL);
755         STAILQ_REMOVE_HEAD(&p->iofhd, io_flist);
756         aior->cfis = cfis;
757         aior->slot = slot;
758         aior->len = 0;
759         aior->done = 0;
760         aior->more = 0;
761         breq = &aior->io_req;
762
763         /*
764          * Mark this command in-flight.
765          */
766         p->pending |= 1 << slot;
767
768         /*
769          * Stuff request onto busy list
770          */
771         TAILQ_INSERT_HEAD(&p->iobhd, aior, io_blist);
772
773         err = blockif_flush(p->bctx, breq);
774         assert(err == 0);
775 }
776
777 static inline void
778 read_prdt(struct ahci_port *p, int slot, uint8_t *cfis,
779                 void *buf, int size)
780 {
781         struct ahci_cmd_hdr *hdr;
782         struct ahci_prdt_entry *prdt;
783         void *to;
784         int i, len;
785
786         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
787         len = size;
788         to = buf;
789         prdt = (struct ahci_prdt_entry *)(cfis + 0x80);
790         for (i = 0; i < hdr->prdtl && len; i++) {
791                 uint8_t *ptr;
792                 uint32_t dbcsz;
793                 int sublen;
794
795                 dbcsz = (prdt->dbc & DBCMASK) + 1;
796                 ptr = paddr_guest2host(ahci_ctx(p->pr_sc), prdt->dba, dbcsz);
797                 sublen = MIN(len, dbcsz);
798                 memcpy(to, ptr, sublen);
799                 len -= sublen;
800                 to += sublen;
801                 prdt++;
802         }
803 }
804
805 static void
806 ahci_handle_dsm_trim(struct ahci_port *p, int slot, uint8_t *cfis, uint32_t done)
807 {
808         struct ahci_ioreq *aior;
809         struct blockif_req *breq;
810         uint8_t *entry;
811         uint64_t elba;
812         uint32_t len, elen;
813         int err, first, ncq;
814         uint8_t buf[512];
815
816         first = (done == 0);
817         if (cfis[2] == ATA_DATA_SET_MANAGEMENT) {
818                 len = (uint16_t)cfis[13] << 8 | cfis[12];
819                 len *= 512;
820                 ncq = 0;
821         } else { /* ATA_SEND_FPDMA_QUEUED */
822                 len = (uint16_t)cfis[11] << 8 | cfis[3];
823                 len *= 512;
824                 ncq = 1;
825         }
826         read_prdt(p, slot, cfis, buf, sizeof(buf));
827
828 next:
829         entry = &buf[done];
830         elba = ((uint64_t)entry[5] << 40) |
831                 ((uint64_t)entry[4] << 32) |
832                 ((uint64_t)entry[3] << 24) |
833                 ((uint64_t)entry[2] << 16) |
834                 ((uint64_t)entry[1] << 8) |
835                 entry[0];
836         elen = (uint16_t)entry[7] << 8 | entry[6];
837         done += 8;
838         if (elen == 0) {
839                 if (done >= len) {
840                         if (ncq) {
841                                 if (first)
842                                         ahci_write_fis_d2h_ncq(p, slot);
843                                 ahci_write_fis_sdb(p, slot, cfis,
844                                     ATA_S_READY | ATA_S_DSC);
845                         } else {
846                                 ahci_write_fis_d2h(p, slot, cfis,
847                                     ATA_S_READY | ATA_S_DSC);
848                         }
849                         p->pending &= ~(1 << slot);
850                         ahci_check_stopped(p);
851                         if (!first)
852                                 ahci_handle_port(p);
853                         return;
854                 }
855                 goto next;
856         }
857
858         /*
859          * Pull request off free list
860          */
861         aior = STAILQ_FIRST(&p->iofhd);
862         assert(aior != NULL);
863         STAILQ_REMOVE_HEAD(&p->iofhd, io_flist);
864         aior->cfis = cfis;
865         aior->slot = slot;
866         aior->len = len;
867         aior->done = done;
868         aior->more = (len != done);
869
870         breq = &aior->io_req;
871         breq->br_offset = elba * blockif_sectsz(p->bctx);
872         breq->br_resid = elen * blockif_sectsz(p->bctx);
873
874         /*
875          * Mark this command in-flight.
876          */
877         p->pending |= 1 << slot;
878
879         /*
880          * Stuff request onto busy list
881          */
882         TAILQ_INSERT_HEAD(&p->iobhd, aior, io_blist);
883
884         if (ncq && first)
885                 ahci_write_fis_d2h_ncq(p, slot);
886
887         err = blockif_delete(p->bctx, breq);
888         assert(err == 0);
889 }
890
891 static inline void
892 write_prdt(struct ahci_port *p, int slot, uint8_t *cfis,
893                 void *buf, int size)
894 {
895         struct ahci_cmd_hdr *hdr;
896         struct ahci_prdt_entry *prdt;
897         void *from;
898         int i, len;
899
900         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
901         len = size;
902         from = buf;
903         prdt = (struct ahci_prdt_entry *)(cfis + 0x80);
904         for (i = 0; i < hdr->prdtl && len; i++) {
905                 uint8_t *ptr;
906                 uint32_t dbcsz;
907                 int sublen;
908
909                 dbcsz = (prdt->dbc & DBCMASK) + 1;
910                 ptr = paddr_guest2host(ahci_ctx(p->pr_sc), prdt->dba, dbcsz);
911                 sublen = MIN(len, dbcsz);
912                 memcpy(ptr, from, sublen);
913                 len -= sublen;
914                 from += sublen;
915                 prdt++;
916         }
917         hdr->prdbc = size - len;
918 }
919
920 static void
921 ahci_checksum(uint8_t *buf, int size)
922 {
923         int i;
924         uint8_t sum = 0;
925
926         for (i = 0; i < size - 1; i++)
927                 sum += buf[i];
928         buf[size - 1] = 0x100 - sum;
929 }
930
931 static void
932 ahci_handle_read_log(struct ahci_port *p, int slot, uint8_t *cfis)
933 {
934         struct ahci_cmd_hdr *hdr;
935         uint32_t buf[128];
936         uint8_t *buf8 = (uint8_t *)buf;
937         uint16_t *buf16 = (uint16_t *)buf;
938
939         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
940         if (p->atapi || hdr->prdtl == 0 || cfis[5] != 0 ||
941             cfis[9] != 0 || cfis[12] != 1 || cfis[13] != 0) {
942                 ahci_write_fis_d2h(p, slot, cfis,
943                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
944                 return;
945         }
946
947         memset(buf, 0, sizeof(buf));
948         if (cfis[4] == 0x00) {  /* Log directory */
949                 buf16[0x00] = 1; /* Version -- 1 */
950                 buf16[0x10] = 1; /* NCQ Command Error Log -- 1 page */
951                 buf16[0x13] = 1; /* SATA NCQ Send and Receive Log -- 1 page */
952         } else if (cfis[4] == 0x10) {   /* NCQ Command Error Log */
953                 memcpy(buf8, p->err_cfis, sizeof(p->err_cfis));
954                 ahci_checksum(buf8, sizeof(buf));
955         } else if (cfis[4] == 0x13) {   /* SATA NCQ Send and Receive Log */
956                 if (blockif_candelete(p->bctx) && !blockif_is_ro(p->bctx)) {
957                         buf[0x00] = 1;  /* SFQ DSM supported */
958                         buf[0x01] = 1;  /* SFQ DSM TRIM supported */
959                 }
960         } else {
961                 ahci_write_fis_d2h(p, slot, cfis,
962                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
963                 return;
964         }
965
966         if (cfis[2] == ATA_READ_LOG_EXT)
967                 ahci_write_fis_piosetup(p);
968         write_prdt(p, slot, cfis, (void *)buf, sizeof(buf));
969         ahci_write_fis_d2h(p, slot, cfis, ATA_S_DSC | ATA_S_READY);
970 }
971
972 static void
973 handle_identify(struct ahci_port *p, int slot, uint8_t *cfis)
974 {
975         struct ahci_cmd_hdr *hdr;
976
977         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
978         if (p->atapi || hdr->prdtl == 0) {
979                 ahci_write_fis_d2h(p, slot, cfis,
980                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
981         } else {
982                 uint16_t buf[256];
983                 uint64_t sectors;
984                 int sectsz, psectsz, psectoff, candelete, ro;
985                 uint16_t cyl;
986                 uint8_t sech, heads;
987
988                 ro = blockif_is_ro(p->bctx);
989                 candelete = blockif_candelete(p->bctx);
990                 sectsz = blockif_sectsz(p->bctx);
991                 sectors = blockif_size(p->bctx) / sectsz;
992                 blockif_chs(p->bctx, &cyl, &heads, &sech);
993                 blockif_psectsz(p->bctx, &psectsz, &psectoff);
994                 memset(buf, 0, sizeof(buf));
995                 buf[0] = 0x0040;
996                 buf[1] = cyl;
997                 buf[3] = heads;
998                 buf[6] = sech;
999                 ata_string((uint8_t *)(buf+10), p->ident, 20);
1000                 ata_string((uint8_t *)(buf+23), "001", 8);
1001                 ata_string((uint8_t *)(buf+27), "BHYVE SATA DISK", 40);
1002                 buf[47] = (0x8000 | 128);
1003                 buf[48] = 0;
1004                 buf[49] = (1 << 8 | 1 << 9 | 1 << 11);
1005                 buf[50] = (1 << 14);
1006                 buf[53] = (1 << 1 | 1 << 2);
1007                 if (p->mult_sectors)
1008                         buf[59] = (0x100 | p->mult_sectors);
1009                 if (sectors <= 0x0fffffff) {
1010                         buf[60] = sectors;
1011                         buf[61] = (sectors >> 16);
1012                 } else {
1013                         buf[60] = 0xffff;
1014                         buf[61] = 0x0fff;
1015                 }
1016                 buf[63] = 0x7;
1017                 if (p->xfermode & ATA_WDMA0)
1018                         buf[63] |= (1 << ((p->xfermode & 7) + 8));
1019                 buf[64] = 0x3;
1020                 buf[65] = 120;
1021                 buf[66] = 120;
1022                 buf[67] = 120;
1023                 buf[68] = 120;
1024                 buf[69] = 0;
1025                 buf[75] = 31;
1026                 buf[76] = (ATA_SATA_GEN1 | ATA_SATA_GEN2 | ATA_SATA_GEN3 |
1027                            ATA_SUPPORT_NCQ);
1028                 buf[77] = (ATA_SUPPORT_RCVSND_FPDMA_QUEUED |
1029                            (p->ssts & ATA_SS_SPD_MASK) >> 3);
1030                 buf[80] = 0x3f0;
1031                 buf[81] = 0x28;
1032                 buf[82] = (ATA_SUPPORT_POWERMGT | ATA_SUPPORT_WRITECACHE|
1033                            ATA_SUPPORT_LOOKAHEAD | ATA_SUPPORT_NOP);
1034                 buf[83] = (ATA_SUPPORT_ADDRESS48 | ATA_SUPPORT_FLUSHCACHE |
1035                            ATA_SUPPORT_FLUSHCACHE48 | 1 << 14);
1036                 buf[84] = (1 << 14);
1037                 buf[85] = (ATA_SUPPORT_POWERMGT | ATA_SUPPORT_WRITECACHE|
1038                            ATA_SUPPORT_LOOKAHEAD | ATA_SUPPORT_NOP);
1039                 buf[86] = (ATA_SUPPORT_ADDRESS48 | ATA_SUPPORT_FLUSHCACHE |
1040                            ATA_SUPPORT_FLUSHCACHE48 | 1 << 15);
1041                 buf[87] = (1 << 14);
1042                 buf[88] = 0x7f;
1043                 if (p->xfermode & ATA_UDMA0)
1044                         buf[88] |= (1 << ((p->xfermode & 7) + 8));
1045                 buf[100] = sectors;
1046                 buf[101] = (sectors >> 16);
1047                 buf[102] = (sectors >> 32);
1048                 buf[103] = (sectors >> 48);
1049                 if (candelete && !ro) {
1050                         buf[69] |= ATA_SUPPORT_RZAT | ATA_SUPPORT_DRAT;
1051                         buf[105] = 1;
1052                         buf[169] = ATA_SUPPORT_DSM_TRIM;
1053                 }
1054                 buf[106] = 0x4000;
1055                 buf[209] = 0x4000;
1056                 if (psectsz > sectsz) {
1057                         buf[106] |= 0x2000;
1058                         buf[106] |= ffsl(psectsz / sectsz) - 1;
1059                         buf[209] |= (psectoff / sectsz);
1060                 }
1061                 if (sectsz > 512) {
1062                         buf[106] |= 0x1000;
1063                         buf[117] = sectsz / 2;
1064                         buf[118] = ((sectsz / 2) >> 16);
1065                 }
1066                 buf[119] = (ATA_SUPPORT_RWLOGDMAEXT | 1 << 14);
1067                 buf[120] = (ATA_SUPPORT_RWLOGDMAEXT | 1 << 14);
1068                 buf[222] = 0x1020;
1069                 buf[255] = 0x00a5;
1070                 ahci_checksum((uint8_t *)buf, sizeof(buf));
1071                 ahci_write_fis_piosetup(p);
1072                 write_prdt(p, slot, cfis, (void *)buf, sizeof(buf));
1073                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_DSC | ATA_S_READY);
1074         }
1075 }
1076
1077 static void
1078 handle_atapi_identify(struct ahci_port *p, int slot, uint8_t *cfis)
1079 {
1080         if (!p->atapi) {
1081                 ahci_write_fis_d2h(p, slot, cfis,
1082                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1083         } else {
1084                 uint16_t buf[256];
1085
1086                 memset(buf, 0, sizeof(buf));
1087                 buf[0] = (2 << 14 | 5 << 8 | 1 << 7 | 2 << 5);
1088                 ata_string((uint8_t *)(buf+10), p->ident, 20);
1089                 ata_string((uint8_t *)(buf+23), "001", 8);
1090                 ata_string((uint8_t *)(buf+27), "BHYVE SATA DVD ROM", 40);
1091                 buf[49] = (1 << 9 | 1 << 8);
1092                 buf[50] = (1 << 14 | 1);
1093                 buf[53] = (1 << 2 | 1 << 1);
1094                 buf[62] = 0x3f;
1095                 buf[63] = 7;
1096                 if (p->xfermode & ATA_WDMA0)
1097                         buf[63] |= (1 << ((p->xfermode & 7) + 8));
1098                 buf[64] = 3;
1099                 buf[65] = 120;
1100                 buf[66] = 120;
1101                 buf[67] = 120;
1102                 buf[68] = 120;
1103                 buf[76] = (ATA_SATA_GEN1 | ATA_SATA_GEN2 | ATA_SATA_GEN3);
1104                 buf[77] = ((p->ssts & ATA_SS_SPD_MASK) >> 3);
1105                 buf[78] = (1 << 5);
1106                 buf[80] = 0x3f0;
1107                 buf[82] = (ATA_SUPPORT_POWERMGT | ATA_SUPPORT_PACKET |
1108                            ATA_SUPPORT_RESET | ATA_SUPPORT_NOP);
1109                 buf[83] = (1 << 14);
1110                 buf[84] = (1 << 14);
1111                 buf[85] = (ATA_SUPPORT_POWERMGT | ATA_SUPPORT_PACKET |
1112                            ATA_SUPPORT_RESET | ATA_SUPPORT_NOP);
1113                 buf[87] = (1 << 14);
1114                 buf[88] = 0x7f;
1115                 if (p->xfermode & ATA_UDMA0)
1116                         buf[88] |= (1 << ((p->xfermode & 7) + 8));
1117                 buf[222] = 0x1020;
1118                 buf[255] = 0x00a5;
1119                 ahci_checksum((uint8_t *)buf, sizeof(buf));
1120                 ahci_write_fis_piosetup(p);
1121                 write_prdt(p, slot, cfis, (void *)buf, sizeof(buf));
1122                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_DSC | ATA_S_READY);
1123         }
1124 }
1125
1126 static void
1127 atapi_inquiry(struct ahci_port *p, int slot, uint8_t *cfis)
1128 {
1129         uint8_t buf[36];
1130         uint8_t *acmd;
1131         int len;
1132         uint32_t tfd;
1133
1134         acmd = cfis + 0x40;
1135
1136         if (acmd[1] & 1) {              /* VPD */
1137                 if (acmd[2] == 0) {     /* Supported VPD pages */
1138                         buf[0] = 0x05;
1139                         buf[1] = 0;
1140                         buf[2] = 0;
1141                         buf[3] = 1;
1142                         buf[4] = 0;
1143                         len = 4 + buf[3];
1144                 } else {
1145                         p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1146                         p->asc = 0x24;
1147                         tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1148                         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1149                         ahci_write_fis_d2h(p, slot, cfis, tfd);
1150                         return;
1151                 }
1152         } else {
1153                 buf[0] = 0x05;
1154                 buf[1] = 0x80;
1155                 buf[2] = 0x00;
1156                 buf[3] = 0x21;
1157                 buf[4] = 31;
1158                 buf[5] = 0;
1159                 buf[6] = 0;
1160                 buf[7] = 0;
1161                 atapi_string(buf + 8, "BHYVE", 8);
1162                 atapi_string(buf + 16, "BHYVE DVD-ROM", 16);
1163                 atapi_string(buf + 32, "001", 4);
1164                 len = sizeof(buf);
1165         }
1166
1167         if (len > acmd[4])
1168                 len = acmd[4];
1169         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1170         write_prdt(p, slot, cfis, buf, len);
1171         ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1172 }
1173
1174 static void
1175 atapi_read_capacity(struct ahci_port *p, int slot, uint8_t *cfis)
1176 {
1177         uint8_t buf[8];
1178         uint64_t sectors;
1179
1180         sectors = blockif_size(p->bctx) / 2048;
1181         be32enc(buf, sectors - 1);
1182         be32enc(buf + 4, 2048);
1183         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1184         write_prdt(p, slot, cfis, buf, sizeof(buf));
1185         ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1186 }
1187
1188 static void
1189 atapi_read_toc(struct ahci_port *p, int slot, uint8_t *cfis)
1190 {
1191         uint8_t *acmd;
1192         uint8_t format;
1193         int len;
1194
1195         acmd = cfis + 0x40;
1196
1197         len = be16dec(acmd + 7);
1198         format = acmd[9] >> 6;
1199         switch (format) {
1200         case 0:
1201         {
1202                 int msf, size;
1203                 uint64_t sectors;
1204                 uint8_t start_track, buf[20], *bp;
1205
1206                 msf = (acmd[1] >> 1) & 1;
1207                 start_track = acmd[6];
1208                 if (start_track > 1 && start_track != 0xaa) {
1209                         uint32_t tfd;
1210                         p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1211                         p->asc = 0x24;
1212                         tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1213                         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1214                         ahci_write_fis_d2h(p, slot, cfis, tfd);
1215                         return;
1216                 }
1217                 bp = buf + 2;
1218                 *bp++ = 1;
1219                 *bp++ = 1;
1220                 if (start_track <= 1) {
1221                         *bp++ = 0;
1222                         *bp++ = 0x14;
1223                         *bp++ = 1;
1224                         *bp++ = 0;
1225                         if (msf) {
1226                                 *bp++ = 0;
1227                                 lba_to_msf(bp, 0);
1228                                 bp += 3;
1229                         } else {
1230                                 *bp++ = 0;
1231                                 *bp++ = 0;
1232                                 *bp++ = 0;
1233                                 *bp++ = 0;
1234                         }
1235                 }
1236                 *bp++ = 0;
1237                 *bp++ = 0x14;
1238                 *bp++ = 0xaa;
1239                 *bp++ = 0;
1240                 sectors = blockif_size(p->bctx) / blockif_sectsz(p->bctx);
1241                 sectors >>= 2;
1242                 if (msf) {
1243                         *bp++ = 0;
1244                         lba_to_msf(bp, sectors);
1245                         bp += 3;
1246                 } else {
1247                         be32enc(bp, sectors);
1248                         bp += 4;
1249                 }
1250                 size = bp - buf;
1251                 be16enc(buf, size - 2);
1252                 if (len > size)
1253                         len = size;
1254                 write_prdt(p, slot, cfis, buf, len);
1255                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1256                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1257                 break;
1258         }
1259         case 1:
1260         {
1261                 uint8_t buf[12];
1262
1263                 memset(buf, 0, sizeof(buf));
1264                 buf[1] = 0xa;
1265                 buf[2] = 0x1;
1266                 buf[3] = 0x1;
1267                 if (len > sizeof(buf))
1268                         len = sizeof(buf);
1269                 write_prdt(p, slot, cfis, buf, len);
1270                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1271                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1272                 break;
1273         }
1274         case 2:
1275         {
1276                 int msf, size;
1277                 uint64_t sectors;
1278                 uint8_t *bp, buf[50];
1279
1280                 msf = (acmd[1] >> 1) & 1;
1281                 bp = buf + 2;
1282                 *bp++ = 1;
1283                 *bp++ = 1;
1284
1285                 *bp++ = 1;
1286                 *bp++ = 0x14;
1287                 *bp++ = 0;
1288                 *bp++ = 0xa0;
1289                 *bp++ = 0;
1290                 *bp++ = 0;
1291                 *bp++ = 0;
1292                 *bp++ = 0;
1293                 *bp++ = 1;
1294                 *bp++ = 0;
1295                 *bp++ = 0;
1296
1297                 *bp++ = 1;
1298                 *bp++ = 0x14;
1299                 *bp++ = 0;
1300                 *bp++ = 0xa1;
1301                 *bp++ = 0;
1302                 *bp++ = 0;
1303                 *bp++ = 0;
1304                 *bp++ = 0;
1305                 *bp++ = 1;
1306                 *bp++ = 0;
1307                 *bp++ = 0;
1308
1309                 *bp++ = 1;
1310                 *bp++ = 0x14;
1311                 *bp++ = 0;
1312                 *bp++ = 0xa2;
1313                 *bp++ = 0;
1314                 *bp++ = 0;
1315                 *bp++ = 0;
1316                 sectors = blockif_size(p->bctx) / blockif_sectsz(p->bctx);
1317                 sectors >>= 2;
1318                 if (msf) {
1319                         *bp++ = 0;
1320                         lba_to_msf(bp, sectors);
1321                         bp += 3;
1322                 } else {
1323                         be32enc(bp, sectors);
1324                         bp += 4;
1325                 }
1326
1327                 *bp++ = 1;
1328                 *bp++ = 0x14;
1329                 *bp++ = 0;
1330                 *bp++ = 1;
1331                 *bp++ = 0;
1332                 *bp++ = 0;
1333                 *bp++ = 0;
1334                 if (msf) {
1335                         *bp++ = 0;
1336                         lba_to_msf(bp, 0);
1337                         bp += 3;
1338                 } else {
1339                         *bp++ = 0;
1340                         *bp++ = 0;
1341                         *bp++ = 0;
1342                         *bp++ = 0;
1343                 }
1344
1345                 size = bp - buf;
1346                 be16enc(buf, size - 2);
1347                 if (len > size)
1348                         len = size;
1349                 write_prdt(p, slot, cfis, buf, len);
1350                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1351                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1352                 break;
1353         }
1354         default:
1355         {
1356                 uint32_t tfd;
1357
1358                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1359                 p->asc = 0x24;
1360                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1361                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1362                 ahci_write_fis_d2h(p, slot, cfis, tfd);
1363                 break;
1364         }
1365         }
1366 }
1367
1368 static void
1369 atapi_report_luns(struct ahci_port *p, int slot, uint8_t *cfis)
1370 {
1371         uint8_t buf[16];
1372
1373         memset(buf, 0, sizeof(buf));
1374         buf[3] = 8;
1375
1376         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1377         write_prdt(p, slot, cfis, buf, sizeof(buf));
1378         ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1379 }
1380
1381 static void
1382 atapi_read(struct ahci_port *p, int slot, uint8_t *cfis, uint32_t done)
1383 {
1384         struct ahci_ioreq *aior;
1385         struct ahci_cmd_hdr *hdr;
1386         struct ahci_prdt_entry *prdt;
1387         struct blockif_req *breq;
1388         uint8_t *acmd;
1389         uint64_t lba;
1390         uint32_t len;
1391         int err;
1392
1393         acmd = cfis + 0x40;
1394         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
1395         prdt = (struct ahci_prdt_entry *)(cfis + 0x80);
1396
1397         lba = be32dec(acmd + 2);
1398         if (acmd[0] == READ_10)
1399                 len = be16dec(acmd + 7);
1400         else
1401                 len = be32dec(acmd + 6);
1402         if (len == 0) {
1403                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1404                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1405         }
1406         lba *= 2048;
1407         len *= 2048;
1408
1409         /*
1410          * Pull request off free list
1411          */
1412         aior = STAILQ_FIRST(&p->iofhd);
1413         assert(aior != NULL);
1414         STAILQ_REMOVE_HEAD(&p->iofhd, io_flist);
1415         aior->cfis = cfis;
1416         aior->slot = slot;
1417         aior->len = len;
1418         aior->done = done;
1419         breq = &aior->io_req;
1420         breq->br_offset = lba + done;
1421         ahci_build_iov(p, aior, prdt, hdr->prdtl);
1422
1423         /* Mark this command in-flight. */
1424         p->pending |= 1 << slot;
1425
1426         /* Stuff request onto busy list. */
1427         TAILQ_INSERT_HEAD(&p->iobhd, aior, io_blist);
1428
1429         err = blockif_read(p->bctx, breq);
1430         assert(err == 0);
1431 }
1432
1433 static void
1434 atapi_request_sense(struct ahci_port *p, int slot, uint8_t *cfis)
1435 {
1436         uint8_t buf[64];
1437         uint8_t *acmd;
1438         int len;
1439
1440         acmd = cfis + 0x40;
1441         len = acmd[4];
1442         if (len > sizeof(buf))
1443                 len = sizeof(buf);
1444         memset(buf, 0, len);
1445         buf[0] = 0x70 | (1 << 7);
1446         buf[2] = p->sense_key;
1447         buf[7] = 10;
1448         buf[12] = p->asc;
1449         write_prdt(p, slot, cfis, buf, len);
1450         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1451         ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1452 }
1453
1454 static void
1455 atapi_start_stop_unit(struct ahci_port *p, int slot, uint8_t *cfis)
1456 {
1457         uint8_t *acmd = cfis + 0x40;
1458         uint32_t tfd;
1459
1460         switch (acmd[4] & 3) {
1461         case 0:
1462         case 1:
1463         case 3:
1464                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1465                 tfd = ATA_S_READY | ATA_S_DSC;
1466                 break;
1467         case 2:
1468                 /* TODO eject media */
1469                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1470                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1471                 p->asc = 0x53;
1472                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1473                 break;
1474         }
1475         ahci_write_fis_d2h(p, slot, cfis, tfd);
1476 }
1477
1478 static void
1479 atapi_mode_sense(struct ahci_port *p, int slot, uint8_t *cfis)
1480 {
1481         uint8_t *acmd;
1482         uint32_t tfd;
1483         uint8_t pc, code;
1484         int len;
1485
1486         acmd = cfis + 0x40;
1487         len = be16dec(acmd + 7);
1488         pc = acmd[2] >> 6;
1489         code = acmd[2] & 0x3f;
1490
1491         switch (pc) {
1492         case 0:
1493                 switch (code) {
1494                 case MODEPAGE_RW_ERROR_RECOVERY:
1495                 {
1496                         uint8_t buf[16];
1497
1498                         if (len > sizeof(buf))
1499                                 len = sizeof(buf);
1500
1501                         memset(buf, 0, sizeof(buf));
1502                         be16enc(buf, 16 - 2);
1503                         buf[2] = 0x70;
1504                         buf[8] = 0x01;
1505                         buf[9] = 16 - 10;
1506                         buf[11] = 0x05;
1507                         write_prdt(p, slot, cfis, buf, len);
1508                         tfd = ATA_S_READY | ATA_S_DSC;
1509                         break;
1510                 }
1511                 case MODEPAGE_CD_CAPABILITIES:
1512                 {
1513                         uint8_t buf[30];
1514
1515                         if (len > sizeof(buf))
1516                                 len = sizeof(buf);
1517
1518                         memset(buf, 0, sizeof(buf));
1519                         be16enc(buf, 30 - 2);
1520                         buf[2] = 0x70;
1521                         buf[8] = 0x2A;
1522                         buf[9] = 30 - 10;
1523                         buf[10] = 0x08;
1524                         buf[12] = 0x71;
1525                         be16enc(&buf[18], 2);
1526                         be16enc(&buf[20], 512);
1527                         write_prdt(p, slot, cfis, buf, len);
1528                         tfd = ATA_S_READY | ATA_S_DSC;
1529                         break;
1530                 }
1531                 default:
1532                         goto error;
1533                         break;
1534                 }
1535                 break;
1536         case 3:
1537                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1538                 p->asc = 0x39;
1539                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1540                 break;
1541 error:
1542         case 1:
1543         case 2:
1544                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1545                 p->asc = 0x24;
1546                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1547                 break;
1548         }
1549         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1550         ahci_write_fis_d2h(p, slot, cfis, tfd);
1551 }
1552
1553 static void
1554 atapi_get_event_status_notification(struct ahci_port *p, int slot,
1555     uint8_t *cfis)
1556 {
1557         uint8_t *acmd;
1558         uint32_t tfd;
1559
1560         acmd = cfis + 0x40;
1561
1562         /* we don't support asynchronous operation */
1563         if (!(acmd[1] & 1)) {
1564                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1565                 p->asc = 0x24;
1566                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1567         } else {
1568                 uint8_t buf[8];
1569                 int len;
1570
1571                 len = be16dec(acmd + 7);
1572                 if (len > sizeof(buf))
1573                         len = sizeof(buf);
1574
1575                 memset(buf, 0, sizeof(buf));
1576                 be16enc(buf, 8 - 2);
1577                 buf[2] = 0x04;
1578                 buf[3] = 0x10;
1579                 buf[5] = 0x02;
1580                 write_prdt(p, slot, cfis, buf, len);
1581                 tfd = ATA_S_READY | ATA_S_DSC;
1582         }
1583         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1584         ahci_write_fis_d2h(p, slot, cfis, tfd);
1585 }
1586
1587 static void
1588 handle_packet_cmd(struct ahci_port *p, int slot, uint8_t *cfis)
1589 {
1590         uint8_t *acmd;
1591
1592         acmd = cfis + 0x40;
1593
1594 #ifdef AHCI_DEBUG
1595         {
1596                 int i;
1597                 DPRINTF("ACMD:");
1598                 for (i = 0; i < 16; i++)
1599                         DPRINTF("%02x ", acmd[i]);
1600                 DPRINTF("\n");
1601         }
1602 #endif
1603
1604         switch (acmd[0]) {
1605         case TEST_UNIT_READY:
1606                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1607                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1608                 break;
1609         case INQUIRY:
1610                 atapi_inquiry(p, slot, cfis);
1611                 break;
1612         case READ_CAPACITY:
1613                 atapi_read_capacity(p, slot, cfis);
1614                 break;
1615         case PREVENT_ALLOW:
1616                 /* TODO */
1617                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1618                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1619                 break;
1620         case READ_TOC:
1621                 atapi_read_toc(p, slot, cfis);
1622                 break;
1623         case REPORT_LUNS:
1624                 atapi_report_luns(p, slot, cfis);
1625                 break;
1626         case READ_10:
1627         case READ_12:
1628                 atapi_read(p, slot, cfis, 0);
1629                 break;
1630         case REQUEST_SENSE:
1631                 atapi_request_sense(p, slot, cfis);
1632                 break;
1633         case START_STOP_UNIT:
1634                 atapi_start_stop_unit(p, slot, cfis);
1635                 break;
1636         case MODE_SENSE_10:
1637                 atapi_mode_sense(p, slot, cfis);
1638                 break;
1639         case GET_EVENT_STATUS_NOTIFICATION:
1640                 atapi_get_event_status_notification(p, slot, cfis);
1641                 break;
1642         default:
1643                 cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1644                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1645                 p->asc = 0x20;
1646                 ahci_write_fis_d2h(p, slot, cfis, (p->sense_key << 12) |
1647                                 ATA_S_READY | ATA_S_ERROR);
1648                 break;
1649         }
1650 }
1651
1652 static void
1653 ahci_handle_cmd(struct ahci_port *p, int slot, uint8_t *cfis)
1654 {
1655
1656         p->tfd |= ATA_S_BUSY;
1657         switch (cfis[2]) {
1658         case ATA_ATA_IDENTIFY:
1659                 handle_identify(p, slot, cfis);
1660                 break;
1661         case ATA_SETFEATURES:
1662         {
1663                 switch (cfis[3]) {
1664                 case ATA_SF_ENAB_SATA_SF:
1665                         switch (cfis[12]) {
1666                         case ATA_SATA_SF_AN:
1667                                 p->tfd = ATA_S_DSC | ATA_S_READY;
1668                                 break;
1669                         default:
1670                                 p->tfd = ATA_S_ERROR | ATA_S_READY;
1671                                 p->tfd |= (ATA_ERROR_ABORT << 8);
1672                                 break;
1673                         }
1674                         break;
1675                 case ATA_SF_ENAB_WCACHE:
1676                 case ATA_SF_DIS_WCACHE:
1677                 case ATA_SF_ENAB_RCACHE:
1678                 case ATA_SF_DIS_RCACHE:
1679                         p->tfd = ATA_S_DSC | ATA_S_READY;
1680                         break;
1681                 case ATA_SF_SETXFER:
1682                 {
1683                         switch (cfis[12] & 0xf8) {
1684                         case ATA_PIO:
1685                         case ATA_PIO0:
1686                                 break;
1687                         case ATA_WDMA0:
1688                         case ATA_UDMA0:
1689                                 p->xfermode = (cfis[12] & 0x7);
1690                                 break;
1691                         }
1692                         p->tfd = ATA_S_DSC | ATA_S_READY;
1693                         break;
1694                 }
1695                 default:
1696                         p->tfd = ATA_S_ERROR | ATA_S_READY;
1697                         p->tfd |= (ATA_ERROR_ABORT << 8);
1698                         break;
1699                 }
1700                 ahci_write_fis_d2h(p, slot, cfis, p->tfd);
1701                 break;
1702         }
1703         case ATA_SET_MULTI:
1704                 if (cfis[12] != 0 &&
1705                         (cfis[12] > 128 || (cfis[12] & (cfis[12] - 1)))) {
1706                         p->tfd = ATA_S_ERROR | ATA_S_READY;
1707                         p->tfd |= (ATA_ERROR_ABORT << 8);
1708                 } else {
1709                         p->mult_sectors = cfis[12];
1710                         p->tfd = ATA_S_DSC | ATA_S_READY;
1711                 }
1712                 ahci_write_fis_d2h(p, slot, cfis, p->tfd);
1713                 break;
1714         case ATA_READ:
1715         case ATA_WRITE:
1716         case ATA_READ48:
1717         case ATA_WRITE48:
1718         case ATA_READ_MUL:
1719         case ATA_WRITE_MUL:
1720         case ATA_READ_MUL48:
1721         case ATA_WRITE_MUL48:
1722         case ATA_READ_DMA:
1723         case ATA_WRITE_DMA:
1724         case ATA_READ_DMA48:
1725         case ATA_WRITE_DMA48:
1726         case ATA_READ_FPDMA_QUEUED:
1727         case ATA_WRITE_FPDMA_QUEUED:
1728                 ahci_handle_rw(p, slot, cfis, 0);
1729                 break;
1730         case ATA_FLUSHCACHE:
1731         case ATA_FLUSHCACHE48:
1732                 ahci_handle_flush(p, slot, cfis);
1733                 break;
1734         case ATA_DATA_SET_MANAGEMENT:
1735                 if (cfis[11] == 0 && cfis[3] == ATA_DSM_TRIM &&
1736                     cfis[13] == 0 && cfis[12] == 1) {
1737                         ahci_handle_dsm_trim(p, slot, cfis, 0);
1738                         break;
1739                 }
1740                 ahci_write_fis_d2h(p, slot, cfis,
1741                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1742                 break;
1743         case ATA_SEND_FPDMA_QUEUED:
1744                 if ((cfis[13] & 0x1f) == ATA_SFPDMA_DSM &&
1745                     cfis[17] == 0 && cfis[16] == ATA_DSM_TRIM &&
1746                     cfis[11] == 0 && cfis[3] == 1) {
1747                         ahci_handle_dsm_trim(p, slot, cfis, 0);
1748                         break;
1749                 }
1750                 ahci_write_fis_d2h(p, slot, cfis,
1751                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1752                 break;
1753         case ATA_READ_LOG_EXT:
1754         case ATA_READ_LOG_DMA_EXT:
1755                 ahci_handle_read_log(p, slot, cfis);
1756                 break;
1757         case ATA_SECURITY_FREEZE_LOCK:
1758         case ATA_SMART_CMD:
1759         case ATA_NOP:
1760                 ahci_write_fis_d2h(p, slot, cfis,
1761                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1762                 break;
1763         case ATA_CHECK_POWER_MODE:
1764                 cfis[12] = 0xff;        /* always on */
1765                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1766                 break;
1767         case ATA_STANDBY_CMD:
1768         case ATA_STANDBY_IMMEDIATE:
1769         case ATA_IDLE_CMD:
1770         case ATA_IDLE_IMMEDIATE:
1771         case ATA_SLEEP:
1772         case ATA_READ_VERIFY:
1773         case ATA_READ_VERIFY48:
1774                 ahci_write_fis_d2h(p, slot, cfis, ATA_S_READY | ATA_S_DSC);
1775                 break;
1776         case ATA_ATAPI_IDENTIFY:
1777                 handle_atapi_identify(p, slot, cfis);
1778                 break;
1779         case ATA_PACKET_CMD:
1780                 if (!p->atapi) {
1781                         ahci_write_fis_d2h(p, slot, cfis,
1782                             (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1783                 } else
1784                         handle_packet_cmd(p, slot, cfis);
1785                 break;
1786         default:
1787                 WPRINTF("Unsupported cmd:%02x\n", cfis[2]);
1788                 ahci_write_fis_d2h(p, slot, cfis,
1789                     (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR);
1790                 break;
1791         }
1792 }
1793
1794 static void
1795 ahci_handle_slot(struct ahci_port *p, int slot)
1796 {
1797         struct ahci_cmd_hdr *hdr;
1798 #ifdef AHCI_DEBUG
1799         struct ahci_prdt_entry *prdt;
1800 #endif
1801         struct pci_ahci_softc *sc;
1802         uint8_t *cfis;
1803 #ifdef AHCI_DEBUG
1804         int cfl, i;
1805 #endif
1806
1807         sc = p->pr_sc;
1808         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
1809 #ifdef AHCI_DEBUG
1810         cfl = (hdr->flags & 0x1f) * 4;
1811 #endif
1812         cfis = paddr_guest2host(ahci_ctx(sc), hdr->ctba,
1813                         0x80 + hdr->prdtl * sizeof(struct ahci_prdt_entry));
1814 #ifdef AHCI_DEBUG
1815         prdt = (struct ahci_prdt_entry *)(cfis + 0x80);
1816
1817         DPRINTF("\ncfis:");
1818         for (i = 0; i < cfl; i++) {
1819                 if (i % 10 == 0)
1820                         DPRINTF("\n");
1821                 DPRINTF("%02x ", cfis[i]);
1822         }
1823         DPRINTF("\n");
1824
1825         for (i = 0; i < hdr->prdtl; i++) {
1826                 DPRINTF("%d@%08"PRIx64"\n", prdt->dbc & 0x3fffff, prdt->dba);
1827                 prdt++;
1828         }
1829 #endif
1830
1831         if (cfis[0] != FIS_TYPE_REGH2D) {
1832                 WPRINTF("Not a H2D FIS:%02x\n", cfis[0]);
1833                 return;
1834         }
1835
1836         if (cfis[1] & 0x80) {
1837                 ahci_handle_cmd(p, slot, cfis);
1838         } else {
1839                 if (cfis[15] & (1 << 2))
1840                         p->reset = 1;
1841                 else if (p->reset) {
1842                         p->reset = 0;
1843                         ahci_port_reset(p);
1844                 }
1845                 p->ci &= ~(1 << slot);
1846         }
1847 }
1848
1849 static void
1850 ahci_handle_port(struct ahci_port *p)
1851 {
1852
1853         if (!(p->cmd & AHCI_P_CMD_ST))
1854                 return;
1855
1856         /*
1857          * Search for any new commands to issue ignoring those that
1858          * are already in-flight.  Stop if device is busy or in error.
1859          */
1860         for (; (p->ci & ~p->pending) != 0; p->ccs = ((p->ccs + 1) & 31)) {
1861                 if ((p->tfd & (ATA_S_BUSY | ATA_S_DRQ)) != 0)
1862                         break;
1863                 if (p->waitforclear)
1864                         break;
1865                 if ((p->ci & ~p->pending & (1 << p->ccs)) != 0) {
1866                         p->cmd &= ~AHCI_P_CMD_CCS_MASK;
1867                         p->cmd |= p->ccs << AHCI_P_CMD_CCS_SHIFT;
1868                         ahci_handle_slot(p, p->ccs);
1869                 }
1870         }
1871 }
1872
1873 /*
1874  * blockif callback routine - this runs in the context of the blockif
1875  * i/o thread, so the mutex needs to be acquired.
1876  */
1877 static void
1878 ata_ioreq_cb(struct blockif_req *br, int err)
1879 {
1880         struct ahci_cmd_hdr *hdr;
1881         struct ahci_ioreq *aior;
1882         struct ahci_port *p;
1883         struct pci_ahci_softc *sc;
1884         uint32_t tfd;
1885         uint8_t *cfis;
1886         int slot, ncq, dsm;
1887
1888         DPRINTF("%s %d\n", __func__, err);
1889
1890         ncq = dsm = 0;
1891         aior = br->br_param;
1892         p = aior->io_pr;
1893         cfis = aior->cfis;
1894         slot = aior->slot;
1895         sc = p->pr_sc;
1896         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + slot * AHCI_CL_SIZE);
1897
1898         if (cfis[2] == ATA_WRITE_FPDMA_QUEUED ||
1899             cfis[2] == ATA_READ_FPDMA_QUEUED ||
1900             cfis[2] == ATA_SEND_FPDMA_QUEUED)
1901                 ncq = 1;
1902         if (cfis[2] == ATA_DATA_SET_MANAGEMENT ||
1903             (cfis[2] == ATA_SEND_FPDMA_QUEUED &&
1904              (cfis[13] & 0x1f) == ATA_SFPDMA_DSM))
1905                 dsm = 1;
1906
1907         pthread_mutex_lock(&sc->mtx);
1908
1909         /*
1910          * Delete the blockif request from the busy list
1911          */
1912         TAILQ_REMOVE(&p->iobhd, aior, io_blist);
1913
1914         /*
1915          * Move the blockif request back to the free list
1916          */
1917         STAILQ_INSERT_TAIL(&p->iofhd, aior, io_flist);
1918
1919         if (!err)
1920                 hdr->prdbc = aior->done;
1921
1922         if (!err && aior->more) {
1923                 if (dsm)
1924                         ahci_handle_dsm_trim(p, slot, cfis, aior->done);
1925                 else 
1926                         ahci_handle_rw(p, slot, cfis, aior->done);
1927                 goto out;
1928         }
1929
1930         if (!err)
1931                 tfd = ATA_S_READY | ATA_S_DSC;
1932         else
1933                 tfd = (ATA_E_ABORT << 8) | ATA_S_READY | ATA_S_ERROR;
1934         if (ncq)
1935                 ahci_write_fis_sdb(p, slot, cfis, tfd);
1936         else
1937                 ahci_write_fis_d2h(p, slot, cfis, tfd);
1938
1939         /*
1940          * This command is now complete.
1941          */
1942         p->pending &= ~(1 << slot);
1943
1944         ahci_check_stopped(p);
1945         ahci_handle_port(p);
1946 out:
1947         pthread_mutex_unlock(&sc->mtx);
1948         DPRINTF("%s exit\n", __func__);
1949 }
1950
1951 static void
1952 atapi_ioreq_cb(struct blockif_req *br, int err)
1953 {
1954         struct ahci_cmd_hdr *hdr;
1955         struct ahci_ioreq *aior;
1956         struct ahci_port *p;
1957         struct pci_ahci_softc *sc;
1958         uint8_t *cfis;
1959         uint32_t tfd;
1960         int slot;
1961
1962         DPRINTF("%s %d\n", __func__, err);
1963
1964         aior = br->br_param;
1965         p = aior->io_pr;
1966         cfis = aior->cfis;
1967         slot = aior->slot;
1968         sc = p->pr_sc;
1969         hdr = (struct ahci_cmd_hdr *)(p->cmd_lst + aior->slot * AHCI_CL_SIZE);
1970
1971         pthread_mutex_lock(&sc->mtx);
1972
1973         /*
1974          * Delete the blockif request from the busy list
1975          */
1976         TAILQ_REMOVE(&p->iobhd, aior, io_blist);
1977
1978         /*
1979          * Move the blockif request back to the free list
1980          */
1981         STAILQ_INSERT_TAIL(&p->iofhd, aior, io_flist);
1982
1983         if (!err)
1984                 hdr->prdbc = aior->done;
1985
1986         if (!err && aior->more) {
1987                 atapi_read(p, slot, cfis, aior->done);
1988                 goto out;
1989         }
1990
1991         if (!err) {
1992                 tfd = ATA_S_READY | ATA_S_DSC;
1993         } else {
1994                 p->sense_key = ATA_SENSE_ILLEGAL_REQUEST;
1995                 p->asc = 0x21;
1996                 tfd = (p->sense_key << 12) | ATA_S_READY | ATA_S_ERROR;
1997         }
1998         cfis[4] = (cfis[4] & ~7) | ATA_I_CMD | ATA_I_IN;
1999         ahci_write_fis_d2h(p, slot, cfis, tfd);
2000
2001         /*
2002          * This command is now complete.
2003          */
2004         p->pending &= ~(1 << slot);
2005
2006         ahci_check_stopped(p);
2007         ahci_handle_port(p);
2008 out:
2009         pthread_mutex_unlock(&sc->mtx);
2010         DPRINTF("%s exit\n", __func__);
2011 }
2012
2013 static void
2014 pci_ahci_ioreq_init(struct ahci_port *pr)
2015 {
2016         struct ahci_ioreq *vr;
2017         int i;
2018
2019         pr->ioqsz = blockif_queuesz(pr->bctx);
2020         pr->ioreq = calloc(pr->ioqsz, sizeof(struct ahci_ioreq));
2021         STAILQ_INIT(&pr->iofhd);
2022
2023         /*
2024          * Add all i/o request entries to the free queue
2025          */
2026         for (i = 0; i < pr->ioqsz; i++) {
2027                 vr = &pr->ioreq[i];
2028                 vr->io_pr = pr;
2029                 if (!pr->atapi)
2030                         vr->io_req.br_callback = ata_ioreq_cb;
2031                 else
2032                         vr->io_req.br_callback = atapi_ioreq_cb;
2033                 vr->io_req.br_param = vr;
2034                 STAILQ_INSERT_TAIL(&pr->iofhd, vr, io_flist);
2035         }
2036
2037         TAILQ_INIT(&pr->iobhd);
2038 }
2039
2040 static void
2041 pci_ahci_port_write(struct pci_ahci_softc *sc, uint64_t offset, uint64_t value)
2042 {
2043         int port = (offset - AHCI_OFFSET) / AHCI_STEP;
2044         offset = (offset - AHCI_OFFSET) % AHCI_STEP;
2045         struct ahci_port *p = &sc->port[port];
2046
2047         DPRINTF("pci_ahci_port %d: write offset 0x%"PRIx64" value 0x%"PRIx64"\n",
2048                 port, offset, value);
2049
2050         switch (offset) {
2051         case AHCI_P_CLB:
2052                 p->clb = value;
2053                 break;
2054         case AHCI_P_CLBU:
2055                 p->clbu = value;
2056                 break;
2057         case AHCI_P_FB:
2058                 p->fb = value;
2059                 break;
2060         case AHCI_P_FBU:
2061                 p->fbu = value;
2062                 break;
2063         case AHCI_P_IS:
2064                 p->is &= ~value;
2065                 ahci_port_intr(p);
2066                 break;
2067         case AHCI_P_IE:
2068                 p->ie = value & 0xFDC000FF;
2069                 ahci_port_intr(p);
2070                 break;
2071         case AHCI_P_CMD:
2072         {
2073                 p->cmd &= ~(AHCI_P_CMD_ST | AHCI_P_CMD_SUD | AHCI_P_CMD_POD |
2074                     AHCI_P_CMD_CLO | AHCI_P_CMD_FRE | AHCI_P_CMD_APSTE |
2075                     AHCI_P_CMD_ATAPI | AHCI_P_CMD_DLAE | AHCI_P_CMD_ALPE |
2076                     AHCI_P_CMD_ASP | AHCI_P_CMD_ICC_MASK);
2077                 p->cmd |= (AHCI_P_CMD_ST | AHCI_P_CMD_SUD | AHCI_P_CMD_POD |
2078                     AHCI_P_CMD_CLO | AHCI_P_CMD_FRE | AHCI_P_CMD_APSTE |
2079                     AHCI_P_CMD_ATAPI | AHCI_P_CMD_DLAE | AHCI_P_CMD_ALPE |
2080                     AHCI_P_CMD_ASP | AHCI_P_CMD_ICC_MASK) & value;
2081
2082                 if (!(value & AHCI_P_CMD_ST)) {
2083                         ahci_port_stop(p);
2084                 } else {
2085                         uint64_t clb;
2086
2087                         p->cmd |= AHCI_P_CMD_CR;
2088                         clb = (uint64_t)p->clbu << 32 | p->clb;
2089                         p->cmd_lst = paddr_guest2host(ahci_ctx(sc), clb,
2090                                         AHCI_CL_SIZE * AHCI_MAX_SLOTS);
2091                 }
2092
2093                 if (value & AHCI_P_CMD_FRE) {
2094                         uint64_t fb;
2095
2096                         p->cmd |= AHCI_P_CMD_FR;
2097                         fb = (uint64_t)p->fbu << 32 | p->fb;
2098                         /* we don't support FBSCP, so rfis size is 256Bytes */
2099                         p->rfis = paddr_guest2host(ahci_ctx(sc), fb, 256);
2100                 } else {
2101                         p->cmd &= ~AHCI_P_CMD_FR;
2102                 }
2103
2104                 if (value & AHCI_P_CMD_CLO) {
2105                         p->tfd &= ~(ATA_S_BUSY | ATA_S_DRQ);
2106                         p->cmd &= ~AHCI_P_CMD_CLO;
2107                 }
2108
2109                 if (value & AHCI_P_CMD_ICC_MASK) {
2110                         p->cmd &= ~AHCI_P_CMD_ICC_MASK;
2111                 }
2112
2113                 ahci_handle_port(p);
2114                 break;
2115         }
2116         case AHCI_P_TFD:
2117         case AHCI_P_SIG:
2118         case AHCI_P_SSTS:
2119                 WPRINTF("pci_ahci_port: read only registers 0x%"PRIx64"\n", offset);
2120                 break;
2121         case AHCI_P_SCTL:
2122                 p->sctl = value;
2123                 if (!(p->cmd & AHCI_P_CMD_ST)) {
2124                         if (value & ATA_SC_DET_RESET)
2125                                 ahci_port_reset(p);
2126                 }
2127                 break;
2128         case AHCI_P_SERR:
2129                 p->serr &= ~value;
2130                 break;
2131         case AHCI_P_SACT:
2132                 p->sact |= value;
2133                 break;
2134         case AHCI_P_CI:
2135                 p->ci |= value;
2136                 ahci_handle_port(p);
2137                 break;
2138         case AHCI_P_SNTF:
2139         case AHCI_P_FBS:
2140         default:
2141                 break;
2142         }
2143 }
2144
2145 static void
2146 pci_ahci_host_write(struct pci_ahci_softc *sc, uint64_t offset, uint64_t value)
2147 {
2148         DPRINTF("pci_ahci_host: write offset 0x%"PRIx64" value 0x%"PRIx64"\n",
2149                 offset, value);
2150
2151         switch (offset) {
2152         case AHCI_CAP:
2153         case AHCI_PI:
2154         case AHCI_VS:
2155         case AHCI_CAP2:
2156                 DPRINTF("pci_ahci_host: read only registers 0x%"PRIx64"\n", offset);
2157                 break;
2158         case AHCI_GHC:
2159                 if (value & AHCI_GHC_HR) {
2160                         ahci_reset(sc);
2161                         break;
2162                 }
2163                 if (value & AHCI_GHC_IE)
2164                         sc->ghc |= AHCI_GHC_IE;
2165                 else
2166                         sc->ghc &= ~AHCI_GHC_IE;
2167                 ahci_generate_intr(sc, 0xffffffff);
2168                 break;
2169         case AHCI_IS:
2170                 sc->is &= ~value;
2171                 ahci_generate_intr(sc, value);
2172                 break;
2173         default:
2174                 break;
2175         }
2176 }
2177
2178 static void
2179 pci_ahci_write(struct vmctx *ctx, int vcpu, struct pci_devinst *pi,
2180                 int baridx, uint64_t offset, int size, uint64_t value)
2181 {
2182         struct pci_ahci_softc *sc = pi->pi_arg;
2183
2184         assert(baridx == 5);
2185         assert((offset % 4) == 0 && size == 4);
2186
2187         pthread_mutex_lock(&sc->mtx);
2188
2189         if (offset < AHCI_OFFSET)
2190                 pci_ahci_host_write(sc, offset, value);
2191         else if (offset < AHCI_OFFSET + sc->ports * AHCI_STEP)
2192                 pci_ahci_port_write(sc, offset, value);
2193         else
2194                 WPRINTF("pci_ahci: unknown i/o write offset 0x%"PRIx64"\n", offset);
2195
2196         pthread_mutex_unlock(&sc->mtx);
2197 }
2198
2199 static uint64_t
2200 pci_ahci_host_read(struct pci_ahci_softc *sc, uint64_t offset)
2201 {
2202         uint32_t value;
2203
2204         switch (offset) {
2205         case AHCI_CAP:
2206         case AHCI_GHC:
2207         case AHCI_IS:
2208         case AHCI_PI:
2209         case AHCI_VS:
2210         case AHCI_CCCC:
2211         case AHCI_CCCP:
2212         case AHCI_EM_LOC:
2213         case AHCI_EM_CTL:
2214         case AHCI_CAP2:
2215         {
2216                 uint32_t *p = &sc->cap;
2217                 p += (offset - AHCI_CAP) / sizeof(uint32_t);
2218                 value = *p;
2219                 break;
2220         }
2221         default:
2222                 value = 0;
2223                 break;
2224         }
2225         DPRINTF("pci_ahci_host: read offset 0x%"PRIx64" value 0x%x\n",
2226                 offset, value);
2227
2228         return (value);
2229 }
2230
2231 static uint64_t
2232 pci_ahci_port_read(struct pci_ahci_softc *sc, uint64_t offset)
2233 {
2234         uint32_t value;
2235         int port = (offset - AHCI_OFFSET) / AHCI_STEP;
2236         offset = (offset - AHCI_OFFSET) % AHCI_STEP;
2237
2238         switch (offset) {
2239         case AHCI_P_CLB:
2240         case AHCI_P_CLBU:
2241         case AHCI_P_FB:
2242         case AHCI_P_FBU:
2243         case AHCI_P_IS:
2244         case AHCI_P_IE:
2245         case AHCI_P_CMD:
2246         case AHCI_P_TFD:
2247         case AHCI_P_SIG:
2248         case AHCI_P_SSTS:
2249         case AHCI_P_SCTL:
2250         case AHCI_P_SERR:
2251         case AHCI_P_SACT:
2252         case AHCI_P_CI:
2253         case AHCI_P_SNTF:
2254         case AHCI_P_FBS:
2255         {
2256                 uint32_t *p= &sc->port[port].clb;
2257                 p += (offset - AHCI_P_CLB) / sizeof(uint32_t);
2258                 value = *p;
2259                 break;
2260         }
2261         default:
2262                 value = 0;
2263                 break;
2264         }
2265
2266         DPRINTF("pci_ahci_port %d: read offset 0x%"PRIx64" value 0x%x\n",
2267                 port, offset, value);
2268
2269         return value;
2270 }
2271
2272 static uint64_t
2273 pci_ahci_read(struct vmctx *ctx, int vcpu, struct pci_devinst *pi, int baridx,
2274     uint64_t regoff, int size)
2275 {
2276         struct pci_ahci_softc *sc = pi->pi_arg;
2277         uint64_t offset;
2278         uint32_t value;
2279
2280         assert(baridx == 5);
2281         assert(size == 1 || size == 2 || size == 4);
2282         assert((regoff & (size - 1)) == 0);
2283
2284         pthread_mutex_lock(&sc->mtx);
2285
2286         offset = regoff & ~0x3;     /* round down to a multiple of 4 bytes */
2287         if (offset < AHCI_OFFSET)
2288                 value = pci_ahci_host_read(sc, offset);
2289         else if (offset < AHCI_OFFSET + sc->ports * AHCI_STEP)
2290                 value = pci_ahci_port_read(sc, offset);
2291         else {
2292                 value = 0;
2293                 WPRINTF("pci_ahci: unknown i/o read offset 0x%"PRIx64"\n",
2294                     regoff);
2295         }
2296         value >>= 8 * (regoff & 0x3);
2297
2298         pthread_mutex_unlock(&sc->mtx);
2299
2300         return (value);
2301 }
2302
2303 static int
2304 pci_ahci_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts, int atapi)
2305 {
2306         char bident[sizeof("XX:XX:XX")];
2307         struct blockif_ctxt *bctxt;
2308         struct pci_ahci_softc *sc;
2309         int ret, slots, p;
2310         MD5_CTX mdctx;
2311         u_char digest[16];
2312         char *next, *next2;
2313
2314         ret = 0;
2315
2316 #ifdef AHCI_DEBUG
2317         dbg = fopen("/tmp/log", "w+");
2318 #endif
2319
2320         sc = calloc(1, sizeof(struct pci_ahci_softc));
2321         pi->pi_arg = sc;
2322         sc->asc_pi = pi;
2323         pthread_mutex_init(&sc->mtx, NULL);
2324         sc->ports = 0;
2325         sc->pi = 0;
2326         slots = 32;
2327
2328         for (p = 0; p < MAX_PORTS && opts != NULL; p++, opts = next) {
2329                 /* Identify and cut off type of present port. */
2330                 if (strncmp(opts, "hd:", 3) == 0) {
2331                         atapi = 0;
2332                         opts += 3;
2333                 } else if (strncmp(opts, "cd:", 3) == 0) {
2334                         atapi = 1;
2335                         opts += 3;
2336                 }
2337
2338                 /* Find and cut off the next port options. */
2339                 next = strstr(opts, ",hd:");
2340                 next2 = strstr(opts, ",cd:");
2341                 if (next == NULL || (next2 != NULL && next2 < next))
2342                         next = next2;
2343                 if (next != NULL) {
2344                         next[0] = 0;
2345                         next++;
2346                 }
2347
2348                 if (opts[0] == 0)
2349                         continue;
2350
2351                 /*
2352                  * Attempt to open the backing image. Use the PCI slot/func
2353                  * and the port number for the identifier string.
2354                  */
2355                 snprintf(bident, sizeof(bident), "%d:%d:%d", pi->pi_slot,
2356                     pi->pi_func, p);
2357                 bctxt = blockif_open(opts, bident);
2358                 if (bctxt == NULL) {
2359                         sc->ports = p;
2360                         ret = 1;
2361                         goto open_fail;
2362                 }       
2363                 sc->port[p].bctx = bctxt;
2364                 sc->port[p].pr_sc = sc;
2365                 sc->port[p].port = p;
2366                 sc->port[p].atapi = atapi;
2367
2368                 /*
2369                  * Create an identifier for the backing file.
2370                  * Use parts of the md5 sum of the filename
2371                  */
2372                 MD5Init(&mdctx);
2373                 MD5Update(&mdctx, opts, strlen(opts));
2374                 MD5Final(digest, &mdctx);
2375                 sprintf(sc->port[p].ident, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
2376                     digest[0], digest[1], digest[2], digest[3], digest[4],
2377                     digest[5]);
2378
2379                 /*
2380                  * Allocate blockif request structures and add them
2381                  * to the free list
2382                  */
2383                 pci_ahci_ioreq_init(&sc->port[p]);
2384
2385                 sc->pi |= (1 << p);
2386                 if (sc->port[p].ioqsz < slots)
2387                         slots = sc->port[p].ioqsz;
2388         }
2389         sc->ports = p;
2390
2391         /* Intel ICH8 AHCI */
2392         --slots;
2393         if (sc->ports < DEF_PORTS)
2394                 sc->ports = DEF_PORTS;
2395         sc->cap = AHCI_CAP_64BIT | AHCI_CAP_SNCQ | AHCI_CAP_SSNTF |
2396             AHCI_CAP_SMPS | AHCI_CAP_SSS | AHCI_CAP_SALP |
2397             AHCI_CAP_SAL | AHCI_CAP_SCLO | (0x3 << AHCI_CAP_ISS_SHIFT)|
2398             AHCI_CAP_PMD | AHCI_CAP_SSC | AHCI_CAP_PSC |
2399             (slots << AHCI_CAP_NCS_SHIFT) | AHCI_CAP_SXS | (sc->ports - 1);
2400
2401         sc->vs = 0x10300;
2402         sc->cap2 = AHCI_CAP2_APST;
2403         ahci_reset(sc);
2404
2405         pci_set_cfgdata16(pi, PCIR_DEVICE, 0x2821);
2406         pci_set_cfgdata16(pi, PCIR_VENDOR, 0x8086);
2407         pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
2408         pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_STORAGE_SATA);
2409         pci_set_cfgdata8(pi, PCIR_PROGIF, PCIP_STORAGE_SATA_AHCI_1_0);
2410         p = MIN(sc->ports, 16);
2411         p = flsl(p) - ((p & (p - 1)) ? 0 : 1);
2412         pci_emul_add_msicap(pi, 1 << p);
2413         pci_emul_alloc_bar(pi, 5, PCIBAR_MEM32,
2414             AHCI_OFFSET + sc->ports * AHCI_STEP);
2415
2416         pci_lintr_request(pi);
2417
2418 open_fail:
2419         if (ret) {
2420                 for (p = 0; p < sc->ports; p++) {
2421                         if (sc->port[p].bctx != NULL)
2422                                 blockif_close(sc->port[p].bctx);
2423                 }
2424                 free(sc);
2425         }
2426
2427         return (ret);
2428 }
2429
2430 static int
2431 pci_ahci_hd_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2432 {
2433
2434         return (pci_ahci_init(ctx, pi, opts, 0));
2435 }
2436
2437 static int
2438 pci_ahci_atapi_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
2439 {
2440
2441         return (pci_ahci_init(ctx, pi, opts, 1));
2442 }
2443
2444 /*
2445  * Use separate emulation names to distinguish drive and atapi devices
2446  */
2447 struct pci_devemu pci_de_ahci = {
2448         .pe_emu =       "ahci",
2449         .pe_init =      pci_ahci_hd_init,
2450         .pe_barwrite =  pci_ahci_write,
2451         .pe_barread =   pci_ahci_read
2452 };
2453 PCI_EMUL_SET(pci_de_ahci);
2454
2455 struct pci_devemu pci_de_ahci_hd = {
2456         .pe_emu =       "ahci-hd",
2457         .pe_init =      pci_ahci_hd_init,
2458         .pe_barwrite =  pci_ahci_write,
2459         .pe_barread =   pci_ahci_read
2460 };
2461 PCI_EMUL_SET(pci_de_ahci_hd);
2462
2463 struct pci_devemu pci_de_ahci_cd = {
2464         .pe_emu =       "ahci-cd",
2465         .pe_init =      pci_ahci_atapi_init,
2466         .pe_barwrite =  pci_ahci_write,
2467         .pe_barread =   pci_ahci_read
2468 };
2469 PCI_EMUL_SET(pci_de_ahci_cd);