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