xref: /openbsd-src/sys/dev/ic/ahci.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: ahci.c,v 1.34 2019/07/08 22:02:59 mlarkin Exp $ */
2 
3 /*
4  * Copyright (c) 2006 David Gwynne <dlg@openbsd.org>
5  * Copyright (c) 2010 Conformal Systems LLC <info@conformal.com>
6  * Copyright (c) 2010 Jonathan Matthew <jonathan@d14n.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/param.h>
22 #include <sys/systm.h>
23 #include <sys/buf.h>
24 #include <sys/kernel.h>
25 #include <sys/malloc.h>
26 #include <sys/device.h>
27 #include <sys/queue.h>
28 #include <sys/mutex.h>
29 #include <sys/pool.h>
30 
31 #include <machine/bus.h>
32 
33 #include <dev/ic/ahcireg.h>
34 #include <dev/ic/ahcivar.h>
35 
36 #ifdef AHCI_DEBUG
37 #define DPRINTF(m, f...) do { if ((ahcidebug & (m)) == (m)) printf(f); } \
38     while (0)
39 #define AHCI_D_TIMEOUT		0x00
40 #define AHCI_D_VERBOSE		0x01
41 #define AHCI_D_INTR		0x02
42 #define AHCI_D_XFER		0x08
43 int ahcidebug = AHCI_D_VERBOSE;
44 #else
45 #define DPRINTF(m, f...)
46 #endif
47 
48 #ifdef HIBERNATE
49 #include <uvm/uvm_extern.h>
50 #include <sys/hibernate.h>
51 #include <sys/disk.h>
52 #include <sys/disklabel.h>
53 
54 #include <scsi/scsi_all.h>
55 #include <scsi/scsiconf.h>
56 
57 void			ahci_hibernate_io_start(struct ahci_port *,
58 			    struct ahci_ccb *);
59 int			ahci_hibernate_io_poll(struct ahci_port *,
60 			    struct ahci_ccb *);
61 void			ahci_hibernate_load_prdt(struct ahci_ccb *);
62 
63 int			ahci_hibernate_io(dev_t dev, daddr_t blkno,
64 			    vaddr_t addr, size_t size, int wr, void *page);
65 #endif
66 
67 struct cfdriver ahci_cd = {
68 	NULL, "ahci", DV_DULL
69 };
70 
71 void			ahci_enable_interrupts(struct ahci_port *);
72 
73 int			ahci_init(struct ahci_softc *);
74 int			ahci_port_alloc(struct ahci_softc *, u_int);
75 void			ahci_port_detect(struct ahci_softc *, u_int);
76 void			ahci_port_free(struct ahci_softc *, u_int);
77 int			ahci_port_init(struct ahci_softc *, u_int);
78 
79 int			ahci_default_port_start(struct ahci_port *, int);
80 int			ahci_port_stop(struct ahci_port *, int);
81 int			ahci_port_clo(struct ahci_port *);
82 int			ahci_port_softreset(struct ahci_port *);
83 void			ahci_port_comreset(struct ahci_port *);
84 int			ahci_port_portreset(struct ahci_port *, int);
85 void			ahci_port_portreset_start(struct ahci_port *);
86 int			ahci_port_portreset_poll(struct ahci_port *);
87 void			ahci_port_portreset_wait(struct ahci_port *);
88 int			ahci_port_portreset_finish(struct ahci_port *, int);
89 int			ahci_port_signature(struct ahci_port *);
90 int			ahci_pmp_port_softreset(struct ahci_port *, int);
91 int			ahci_pmp_port_portreset(struct ahci_port *, int);
92 int			ahci_pmp_port_probe(struct ahci_port *ap, int pmp_port);
93 
94 int			ahci_load_prdt(struct ahci_ccb *);
95 void			ahci_load_prdt_seg(struct ahci_prdt *, u_int64_t,
96 			    u_int32_t, u_int32_t);
97 void			ahci_unload_prdt(struct ahci_ccb *);
98 
99 int			ahci_poll(struct ahci_ccb *, int, void (*)(void *));
100 void			ahci_start(struct ahci_ccb *);
101 
102 void			ahci_issue_pending_ncq_commands(struct ahci_port *);
103 void			ahci_issue_pending_commands(struct ahci_port *, int);
104 
105 int			ahci_intr(void *);
106 u_int32_t		ahci_port_intr(struct ahci_port *, u_int32_t);
107 
108 struct ahci_ccb		*ahci_get_ccb(struct ahci_port *);
109 void			ahci_put_ccb(struct ahci_ccb *);
110 
111 struct ahci_ccb		*ahci_get_err_ccb(struct ahci_port *);
112 void			ahci_put_err_ccb(struct ahci_ccb *);
113 
114 struct ahci_ccb		*ahci_get_pmp_ccb(struct ahci_port *);
115 void			ahci_put_pmp_ccb(struct ahci_ccb *);
116 
117 int			ahci_port_read_ncq_error(struct ahci_port *, int *, int);
118 
119 struct ahci_dmamem	*ahci_dmamem_alloc(struct ahci_softc *, size_t);
120 void			ahci_dmamem_free(struct ahci_softc *,
121 			    struct ahci_dmamem *);
122 
123 u_int32_t		ahci_read(struct ahci_softc *, bus_size_t);
124 void			ahci_write(struct ahci_softc *, bus_size_t, u_int32_t);
125 int			ahci_wait_ne(struct ahci_softc *, bus_size_t,
126 			    u_int32_t, u_int32_t);
127 
128 u_int32_t		ahci_pread(struct ahci_port *, bus_size_t);
129 void			ahci_pwrite(struct ahci_port *, bus_size_t, u_int32_t);
130 int			ahci_pwait_eq(struct ahci_port *, bus_size_t,
131 			    u_int32_t, u_int32_t, int);
132 void			ahci_flush_tfd(struct ahci_port *ap);
133 u_int32_t		ahci_active_mask(struct ahci_port *);
134 int			ahci_port_detect_pmp(struct ahci_port *);
135 void			ahci_pmp_probe_timeout(void *);
136 
137 /* pmp operations */
138 int			ahci_pmp_read(struct ahci_port *, int, int,
139 			    u_int32_t *);
140 int			ahci_pmp_write(struct ahci_port *, int, int, u_int32_t);
141 int			ahci_pmp_phy_status(struct ahci_port *, int,
142 			    u_int32_t *);
143 int 			ahci_pmp_identify(struct ahci_port *, int *);
144 
145 
146 /* Wait for all bits in _b to be cleared */
147 #define ahci_pwait_clr(_ap, _r, _b, _n) \
148    ahci_pwait_eq((_ap), (_r), (_b), 0, (_n))
149 
150 /* Wait for all bits in _b to be set */
151 #define ahci_pwait_set(_ap, _r, _b, _n) \
152    ahci_pwait_eq((_ap), (_r), (_b), (_b), (_n))
153 
154 
155 
156 /* provide methods for atascsi to call */
157 int			ahci_ata_probe(void *, int, int);
158 void			ahci_ata_free(void *, int, int);
159 struct ata_xfer *	ahci_ata_get_xfer(void *, int);
160 void			ahci_ata_put_xfer(struct ata_xfer *);
161 void			ahci_ata_cmd(struct ata_xfer *);
162 
163 struct atascsi_methods ahci_atascsi_methods = {
164 	ahci_ata_probe,
165 	ahci_ata_free,
166 	ahci_ata_get_xfer,
167 	ahci_ata_put_xfer,
168 	ahci_ata_cmd
169 };
170 
171 /* ccb completions */
172 void			ahci_ata_cmd_done(struct ahci_ccb *);
173 void			ahci_pmp_cmd_done(struct ahci_ccb *);
174 void			ahci_ata_cmd_timeout(void *);
175 void			ahci_empty_done(struct ahci_ccb *);
176 
177 int
178 ahci_attach(struct ahci_softc *sc)
179 {
180 	struct atascsi_attach_args	aaa;
181 	u_int32_t			pi;
182 	int				i, j, done;
183 
184 	if (sc->sc_port_start == NULL)
185 		sc->sc_port_start = ahci_default_port_start;
186 
187 	if (ahci_init(sc) != 0) {
188 		/* error already printed by ahci_init */
189 		goto unmap;
190 	}
191 
192 	printf("\n");
193 
194 	sc->sc_cap = ahci_read(sc, AHCI_REG_CAP);
195 	sc->sc_ncmds = AHCI_REG_CAP_NCS(sc->sc_cap);
196 #ifdef AHCI_DEBUG
197 	if (ahcidebug & AHCI_D_VERBOSE) {
198 		const char *gen;
199 
200 		switch (sc->sc_cap & AHCI_REG_CAP_ISS) {
201 		case AHCI_REG_CAP_ISS_G1:
202 			gen = "1 (1.5Gbps)";
203 			break;
204 		case AHCI_REG_CAP_ISS_G2:
205 			gen = "2 (3.0Gb/s)";
206 			break;
207 		case AHCI_REG_CAP_ISS_G3:
208 			gen = "3 (6.0Gb/s)";
209 			break;
210 		default:
211 			gen = "unknown";
212 			break;
213 		}
214 
215 		printf("%s: capabilities 0x%b, %d ports, %d cmds, gen %s\n",
216 		    DEVNAME(sc), sc->sc_cap, AHCI_FMT_CAP,
217 		    AHCI_REG_CAP_NP(sc->sc_cap), sc->sc_ncmds, gen);
218 		printf("%s: extended capabilities 0x%b\n", DEVNAME(sc),
219 		    ahci_read(sc, AHCI_REG_CAP2), AHCI_FMT_CAP2);
220 	}
221 #endif
222 
223 	pi = ahci_read(sc, AHCI_REG_PI);
224 	DPRINTF(AHCI_D_VERBOSE, "%s: ports implemented: 0x%08x\n",
225 	    DEVNAME(sc), pi);
226 
227 #ifdef AHCI_COALESCE
228 	/* Naive coalescing support - enable for all ports. */
229 	if (sc->sc_cap & AHCI_REG_CAP_CCCS) {
230 		u_int16_t		ccc_timeout = 20;
231 		u_int8_t		ccc_numcomplete = 12;
232 		u_int32_t		ccc_ctl;
233 
234 		/* disable coalescing during reconfiguration. */
235 		ccc_ctl = ahci_read(sc, AHCI_REG_CCC_CTL);
236 		ccc_ctl &= ~0x00000001;
237 		ahci_write(sc, AHCI_REG_CCC_CTL, ccc_ctl);
238 
239 		sc->sc_ccc_mask = 1 << AHCI_REG_CCC_CTL_INT(ccc_ctl);
240 		if (pi & sc->sc_ccc_mask) {
241 			/* A conflict with the implemented port list? */
242 			printf("%s: coalescing interrupt/implemented port list "
243 			    "conflict, PI: %08x, ccc_mask: %08x\n",
244 			    DEVNAME(sc), pi, sc->sc_ccc_mask);
245 			sc->sc_ccc_mask = 0;
246 			goto noccc;
247 		}
248 
249 		/* ahci_port_start will enable each port when it starts. */
250 		sc->sc_ccc_ports = pi;
251 		sc->sc_ccc_ports_cur = 0;
252 
253 		/* program thresholds and enable overall coalescing. */
254 		ccc_ctl &= ~0xffffff00;
255 		ccc_ctl |= (ccc_timeout << 16) | (ccc_numcomplete << 8);
256 		ahci_write(sc, AHCI_REG_CCC_CTL, ccc_ctl);
257 		ahci_write(sc, AHCI_REG_CCC_PORTS, 0);
258 		ahci_write(sc, AHCI_REG_CCC_CTL, ccc_ctl | 1);
259 	}
260 noccc:
261 #endif
262 	/*
263 	 * Given that ahci_port_alloc() will grab one CCB for error recovery
264 	 * in the NCQ case from the pool of CCBs sized based on sc->sc_ncmds
265 	 * pretend at least 2 command slots for devices without NCQ support.
266 	 * That way, also at least 1 slot is made available for atascsi(4).
267 	 */
268 	sc->sc_ncmds = max(2, sc->sc_ncmds);
269 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
270 		if (!ISSET(pi, 1 << i)) {
271 			/* dont allocate stuff if the port isnt implemented */
272 			continue;
273 		}
274 
275 		if (ahci_port_alloc(sc, i) == ENOMEM)
276 			goto freeports;
277 
278 		if (sc->sc_ports[i] != NULL)
279 			ahci_port_portreset_start(sc->sc_ports[i]);
280 	}
281 
282 	/*
283 	 * Poll for device detection until all ports report a device, or one
284 	 * second has elapsed.
285 	 */
286 	for (i = 0; i < 1000; i++) {
287 		done = 1;
288 		for (j = 0; j < AHCI_MAX_PORTS; j++) {
289 			if (sc->sc_ports[j] == NULL)
290 				continue;
291 
292 			if (ahci_port_portreset_poll(sc->sc_ports[j]))
293 				done = 0;
294 		}
295 
296 		if (done)
297 			break;
298 
299 		delay(1000);
300 	}
301 
302 	/*
303 	 * Finish device detection on all ports that initialized.
304 	 */
305 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
306 		if (sc->sc_ports[i] != NULL)
307 			ahci_port_detect(sc, i);
308 	}
309 
310 	memset(&aaa, 0, sizeof(aaa));
311 	aaa.aaa_cookie = sc;
312 	aaa.aaa_methods = &ahci_atascsi_methods;
313 	aaa.aaa_minphys = NULL;
314 	aaa.aaa_nports = AHCI_MAX_PORTS;
315 	aaa.aaa_ncmds = sc->sc_ncmds - 1;
316 	if (!(sc->sc_flags & AHCI_F_NO_NCQ) &&
317 	    sc->sc_ncmds > 2 &&
318 	    (sc->sc_cap & AHCI_REG_CAP_SNCQ)) {
319 		aaa.aaa_capability |= ASAA_CAP_NCQ | ASAA_CAP_PMP_NCQ;
320 	}
321 
322 	sc->sc_atascsi = atascsi_attach(&sc->sc_dev, &aaa);
323 
324 	/* Enable interrupts */
325 	ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE | AHCI_REG_GHC_IE);
326 
327 	return 0;
328 
329 freeports:
330 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
331 		if (sc->sc_ports[i] != NULL)
332 			ahci_port_free(sc, i);
333 	}
334 unmap:
335 	/* Disable controller */
336 	ahci_write(sc, AHCI_REG_GHC, 0);
337 	return 1;
338 }
339 
340 int
341 ahci_detach(struct ahci_softc *sc, int flags)
342 {
343 	int				 rv, i;
344 
345 	if (sc->sc_atascsi != NULL) {
346 		rv = atascsi_detach(sc->sc_atascsi, flags);
347 		if (rv != 0)
348 			return (rv);
349 	}
350 
351 	for (i = 0; i < AHCI_MAX_PORTS; i++) {
352 		if (sc->sc_ports[i] != NULL)
353 			ahci_port_free(sc, i);
354 	}
355 
356 	return (0);
357 }
358 
359 int
360 ahci_activate(struct device *self, int act)
361 {
362 	struct ahci_softc		*sc = (struct ahci_softc *)self;
363 	int				 i, rv = 0;
364 
365 	switch (act) {
366 	case DVACT_RESUME:
367 		/* enable ahci (global interrupts disabled) */
368 		ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE);
369 
370 		/* restore BIOS initialised parameters */
371 		ahci_write(sc, AHCI_REG_CAP, sc->sc_cap);
372 
373 		for (i = 0; i < AHCI_MAX_PORTS; i++) {
374 			if (sc->sc_ports[i] != NULL)
375 				ahci_port_init(sc, i);
376 		}
377 
378 		/* Enable interrupts */
379 		ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE | AHCI_REG_GHC_IE);
380 
381 		rv = config_activate_children(self, act);
382 		break;
383 	case DVACT_POWERDOWN:
384 		rv = config_activate_children(self, act);
385 		for (i = 0; i < AHCI_MAX_PORTS; i++) {
386 			if (sc->sc_ports[i] != NULL)
387 				ahci_port_stop(sc->sc_ports[i], 1);
388 		}
389 		break;
390 	default:
391 		rv = config_activate_children(self, act);
392 		break;
393 	}
394 	return (rv);
395 }
396 
397 int
398 ahci_init(struct ahci_softc *sc)
399 {
400 	u_int32_t			reg, cap, pi;
401 	const char			*revision;
402 
403 	DPRINTF(AHCI_D_VERBOSE, " GHC 0x%b", ahci_read(sc, AHCI_REG_GHC),
404 	    AHCI_FMT_GHC);
405 
406 	/* save BIOS initialised parameters, enable staggered spin up */
407 	cap = ahci_read(sc, AHCI_REG_CAP);
408 	cap &= AHCI_REG_CAP_SMPS;
409 	cap |= AHCI_REG_CAP_SSS;
410 	pi = ahci_read(sc, AHCI_REG_PI);
411 
412 	if (ISSET(AHCI_REG_GHC_AE, ahci_read(sc, AHCI_REG_GHC))) {
413 		/* reset the controller */
414 		ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR);
415 		if (ahci_wait_ne(sc, AHCI_REG_GHC, AHCI_REG_GHC_HR,
416 		    AHCI_REG_GHC_HR) != 0) {
417 			printf(" unable to reset controller\n");
418 			return (1);
419 		}
420 	}
421 
422 	/* enable ahci (global interrupts disabled) */
423 	ahci_write(sc, AHCI_REG_GHC, AHCI_REG_GHC_AE);
424 
425 	/* restore parameters */
426 	ahci_write(sc, AHCI_REG_CAP, cap);
427 	ahci_write(sc, AHCI_REG_PI, pi);
428 
429 	/* check the revision */
430 	reg = ahci_read(sc, AHCI_REG_VS);
431 	switch (reg) {
432 	case AHCI_REG_VS_0_95:
433 		revision = "0.95";
434 		break;
435 	case AHCI_REG_VS_1_0:
436 		revision = "1.0";
437 		break;
438 	case AHCI_REG_VS_1_1:
439 		revision = "1.1";
440 		break;
441 	case AHCI_REG_VS_1_2:
442 		revision = "1.2";
443 		break;
444 	case AHCI_REG_VS_1_3:
445 		revision = "1.3";
446 		break;
447 	case AHCI_REG_VS_1_3_1:
448 		revision = "1.3.1";
449 		break;
450 
451 	default:
452 		printf(" unsupported AHCI revision 0x%08x\n", reg);
453 		return (1);
454 	}
455 
456 	printf(" AHCI %s", revision);
457 
458 	return (0);
459 }
460 
461 void
462 ahci_enable_interrupts(struct ahci_port *ap)
463 {
464 	ahci_pwrite(ap, AHCI_PREG_IE, AHCI_PREG_IE_TFEE | AHCI_PREG_IE_HBFE |
465 	    AHCI_PREG_IE_IFE | AHCI_PREG_IE_OFE | AHCI_PREG_IE_DPE |
466 	    AHCI_PREG_IE_UFE |
467 	    ((ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF) ? AHCI_PREG_IE_IPME : 0) |
468 #ifdef AHCI_COALESCE
469 	    ((ap->ap_sc->sc_ccc_ports & (1 << ap->ap_port)) ? 0 :
470 	     (AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE))
471 #else
472 	    AHCI_PREG_IE_SDBE | AHCI_PREG_IE_DHRE
473 #endif
474 	    );
475 }
476 
477 int
478 ahci_port_alloc(struct ahci_softc *sc, u_int port)
479 {
480 	struct ahci_port		*ap;
481 	struct ahci_ccb			*ccb;
482 	u_int64_t			dva;
483 	u_int32_t			cmd;
484 	struct ahci_cmd_hdr		*hdr;
485 	struct ahci_cmd_table		*table;
486 	int				i, rc = ENOMEM;
487 
488 	ap = malloc(sizeof(*ap), M_DEVBUF, M_NOWAIT | M_ZERO);
489 	if (ap == NULL) {
490 		printf("%s: unable to allocate memory for port %d\n",
491 		    DEVNAME(sc), port);
492 		goto reterr;
493 	}
494 	ap->ap_err_scratch = dma_alloc(DEV_BSIZE, PR_NOWAIT | PR_ZERO);
495 	if (ap->ap_err_scratch == NULL) {
496 		printf("%s: unable to allocate DMA scratch buf for port %d\n",
497 		    DEVNAME(sc), port);
498 		free(ap, M_DEVBUF, sizeof(*ap));
499 		goto reterr;
500 	}
501 
502 #ifdef AHCI_DEBUG
503 	snprintf(ap->ap_name, sizeof(ap->ap_name), "%s.%d",
504 	    DEVNAME(sc), port);
505 #endif
506 	ap->ap_port = port;
507 	sc->sc_ports[port] = ap;
508 
509 	if (bus_space_subregion(sc->sc_iot, sc->sc_ioh,
510 	    AHCI_PORT_REGION(port), AHCI_PORT_SIZE, &ap->ap_ioh) != 0) {
511 		printf("%s: unable to create register window for port %d\n",
512 		    DEVNAME(sc), port);
513 		goto freeport;
514 	}
515 
516 	ap->ap_sc = sc;
517 #ifdef AHCI_COALESCE
518 	ap->ap_num = port;
519 #endif
520 	TAILQ_INIT(&ap->ap_ccb_free);
521 	TAILQ_INIT(&ap->ap_ccb_pending);
522 	mtx_init(&ap->ap_ccb_mtx, IPL_BIO);
523 
524 	/* Disable port interrupts */
525 	ahci_pwrite(ap, AHCI_PREG_IE, 0);
526 
527 	/* Sec 10.1.2 - deinitialise port if it is already running */
528 	cmd = ahci_pread(ap, AHCI_PREG_CMD);
529 	if (ISSET(cmd, (AHCI_PREG_CMD_ST | AHCI_PREG_CMD_CR |
530 	    AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_FR)) ||
531 	    ISSET(ahci_pread(ap, AHCI_PREG_SCTL), AHCI_PREG_SCTL_DET)) {
532 		int r;
533 
534 		r = ahci_port_stop(ap, 1);
535 		if (r) {
536 			printf("%s: unable to disable %s, ignoring port %d\n",
537 			    DEVNAME(sc), r == 2 ? "CR" : "FR", port);
538 			rc = ENXIO;
539 			goto freeport;
540 		}
541 
542 		/* Write DET to zero */
543 		ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
544 	}
545 
546 	/* Allocate RFIS */
547 	ap->ap_dmamem_rfis = ahci_dmamem_alloc(sc, sizeof(struct ahci_rfis));
548 	if (ap->ap_dmamem_rfis == NULL)
549 		goto nomem;
550 
551 	/* Setup RFIS base address */
552 	ap->ap_rfis = (struct ahci_rfis *) AHCI_DMA_KVA(ap->ap_dmamem_rfis);
553 	dva = AHCI_DMA_DVA(ap->ap_dmamem_rfis);
554 	ahci_pwrite(ap, AHCI_PREG_FBU, (u_int32_t)(dva >> 32));
555 	ahci_pwrite(ap, AHCI_PREG_FB, (u_int32_t)dva);
556 
557 	/* Enable FIS reception and activate port. */
558 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
559 	cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD | AHCI_PREG_CMD_SUD;
560 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
561 
562 	/* Check whether port activated.  Skip it if not. */
563 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
564 	if (!ISSET(cmd, AHCI_PREG_CMD_FRE)) {
565 		rc = ENXIO;
566 		goto freeport;
567 	}
568 
569 	/* Allocate a CCB for each command slot */
570 	ap->ap_ccbs = mallocarray(sc->sc_ncmds, sizeof(struct ahci_ccb),
571 	    M_DEVBUF, M_NOWAIT | M_ZERO);
572 	if (ap->ap_ccbs == NULL) {
573 		printf("%s: unable to allocate command list for port %d\n",
574 		    DEVNAME(sc), port);
575 		goto freeport;
576 	}
577 
578 	/* Command List Structures and Command Tables */
579 	ap->ap_dmamem_cmd_list = ahci_dmamem_alloc(sc,
580 	    sc->sc_ncmds * sizeof(struct ahci_cmd_hdr));
581 	ap->ap_dmamem_cmd_table = ahci_dmamem_alloc(sc,
582 	    sc->sc_ncmds * sizeof(struct ahci_cmd_table));
583 	if (ap->ap_dmamem_cmd_table == NULL || ap->ap_dmamem_cmd_list == NULL) {
584 nomem:
585 		printf("%s: unable to allocate DMA memory for port %d\n",
586 		    DEVNAME(sc), port);
587 		goto freeport;
588 	}
589 
590 	/* Setup command list base address */
591 	dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_list);
592 	ahci_pwrite(ap, AHCI_PREG_CLBU, (u_int32_t)(dva >> 32));
593 	ahci_pwrite(ap, AHCI_PREG_CLB, (u_int32_t)dva);
594 
595 	/* Split CCB allocation into CCBs and assign to command header/table */
596 	hdr = AHCI_DMA_KVA(ap->ap_dmamem_cmd_list);
597 	table = AHCI_DMA_KVA(ap->ap_dmamem_cmd_table);
598 	for (i = 0; i < sc->sc_ncmds; i++) {
599 		ccb = &ap->ap_ccbs[i];
600 
601 		if (bus_dmamap_create(sc->sc_dmat, MAXPHYS, AHCI_MAX_PRDT,
602 		    (4 * 1024 * 1024), 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW,
603 		    &ccb->ccb_dmamap) != 0) {
604 			printf("%s: unable to create dmamap for port %d "
605 			    "ccb %d\n", DEVNAME(sc), port, i);
606 			goto freeport;
607 		}
608 
609 		ccb->ccb_slot = i;
610 		ccb->ccb_port = ap;
611 		ccb->ccb_cmd_hdr = &hdr[i];
612 		ccb->ccb_cmd_table = &table[i];
613 		htolem64(&ccb->ccb_cmd_hdr->ctba,
614 		    AHCI_DMA_DVA(ap->ap_dmamem_cmd_table) +
615 		    ccb->ccb_slot * sizeof(struct ahci_cmd_table));
616 
617 		ccb->ccb_xa.fis =
618 		    (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
619 		ccb->ccb_xa.packetcmd = ccb->ccb_cmd_table->acmd;
620 		ccb->ccb_xa.tag = i;
621 
622 		ccb->ccb_xa.state = ATA_S_COMPLETE;
623 		ahci_put_ccb(ccb);
624 	}
625 
626 	/* grab a ccb for use during error recovery */
627 	ap->ap_ccb_err = &ap->ap_ccbs[sc->sc_ncmds - 1];
628 	TAILQ_REMOVE(&ap->ap_ccb_free, ap->ap_ccb_err, ccb_entry);
629 	ap->ap_ccb_err->ccb_xa.state = ATA_S_COMPLETE;
630 
631 	/* Wait for ICC change to complete */
632 	ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC, 1);
633 	rc = 0;
634 
635 freeport:
636 	if (rc != 0)
637 		ahci_port_free(sc, port);
638 reterr:
639 	return (rc);
640 }
641 
642 void
643 ahci_port_detect(struct ahci_softc *sc, u_int port)
644 {
645 	struct ahci_port		*ap;
646 	const char			*speed;
647 	int				rc;
648 
649 	ap = sc->sc_ports[port];
650 
651 	rc = ahci_port_portreset_finish(ap, 1);
652 	switch (rc) {
653 	case ENODEV:
654 		switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
655 		case AHCI_PREG_SSTS_DET_DEV_NE:
656 			printf("%s: device not communicating on port %d\n",
657 			    DEVNAME(sc), port);
658 			break;
659 		case AHCI_PREG_SSTS_DET_PHYOFFLINE:
660 			printf("%s: PHY offline on port %d\n", DEVNAME(sc),
661 			    port);
662 			break;
663 		default:
664 			DPRINTF(AHCI_D_VERBOSE, "%s: no device detected "
665 			    "on port %d\n", DEVNAME(sc), port);
666 			break;
667 		}
668 		goto freeport;
669 
670 	case EBUSY:
671 		printf("%s: device on port %d didn't come ready, "
672 		    "TFD: 0x%b\n", DEVNAME(sc), port,
673 		    ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
674 
675 		/* Try a soft reset to clear busy */
676 		rc = ahci_port_softreset(ap);
677 		if (rc) {
678 			printf("%s: unable to communicate "
679 			    "with device on port %d\n", DEVNAME(sc), port);
680 			goto freeport;
681 		}
682 		break;
683 
684 	default:
685 		break;
686 	}
687 
688 	DPRINTF(AHCI_D_VERBOSE, "%s: detected device on port %d; %d\n",
689 	    DEVNAME(sc), port, rc);
690 
691 	/* Read current link speed */
692 	switch(ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_SPD) {
693 	case AHCI_PREG_SSTS_SPD_GEN1:
694 		speed = "1.5Gb/s";
695 		break;
696 	case AHCI_PREG_SSTS_SPD_GEN2:
697 		speed = "3.0Gb/s";
698 		break;
699 	case AHCI_PREG_SSTS_SPD_GEN3:
700 		speed = "6.0Gb/s";
701 		break;
702 	default:
703 		speed = NULL;
704 		break;
705 	}
706 	if (speed != NULL)
707 		printf("%s: port %d: %s\n", PORTNAME(ap), port, speed);
708 
709 	/* Enable command transfers on port */
710 	if (ahci_port_start(ap, 0)) {
711 		printf("%s: failed to start command DMA on port %d, "
712 		    "disabling\n", DEVNAME(sc), port);
713 		rc = ENXIO;	/* couldn't start port */
714 	}
715 
716 	/* Flush interrupts for port */
717 	ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
718 	ahci_write(sc, AHCI_REG_IS, 1 << port);
719 
720 	ahci_enable_interrupts(ap);
721 freeport:
722 	if (rc != 0)
723 		ahci_port_free(sc, port);
724 }
725 
726 void
727 ahci_port_free(struct ahci_softc *sc, u_int port)
728 {
729 	struct ahci_port		*ap = sc->sc_ports[port];
730 	struct ahci_ccb			*ccb;
731 
732 	/* Ensure port is disabled and its interrupts are flushed */
733 	if (ap->ap_sc) {
734 		ahci_pwrite(ap, AHCI_PREG_CMD, 0);
735 		ahci_pwrite(ap, AHCI_PREG_IE, 0);
736 		ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
737 		ahci_write(sc, AHCI_REG_IS, 1 << port);
738 	}
739 
740 	if (ap->ap_ccb_err)
741 		ahci_put_ccb(ap->ap_ccb_err);
742 
743 	if (ap->ap_ccbs) {
744 		while ((ccb = ahci_get_ccb(ap)) != NULL)
745 			bus_dmamap_destroy(sc->sc_dmat, ccb->ccb_dmamap);
746 		free(ap->ap_ccbs, M_DEVBUF, sc->sc_ncmds * sizeof(*ccb));
747 	}
748 
749 	if (ap->ap_dmamem_cmd_list)
750 		ahci_dmamem_free(sc, ap->ap_dmamem_cmd_list);
751 	if (ap->ap_dmamem_rfis)
752 		ahci_dmamem_free(sc, ap->ap_dmamem_rfis);
753 	if (ap->ap_dmamem_cmd_table)
754 		ahci_dmamem_free(sc, ap->ap_dmamem_cmd_table);
755 	if (ap->ap_err_scratch)
756 		dma_free(ap->ap_err_scratch, DEV_BSIZE);
757 
758 	/* bus_space(9) says we dont free the subregions handle */
759 
760 	free(ap, M_DEVBUF, sizeof(*ap));
761 	sc->sc_ports[port] = NULL;
762 }
763 
764 int
765 ahci_port_init(struct ahci_softc *sc, u_int port)
766 {
767 	struct ahci_port		*ap;
768 	u_int64_t			dva;
769 	u_int32_t			cmd;
770 	int				rc = ENOMEM;
771 
772 	ap = sc->sc_ports[port];
773 #ifdef AHCI_DEBUG
774 	snprintf(ap->ap_name, sizeof(ap->ap_name), "%s.%d",
775 	    DEVNAME(sc), port);
776 #endif
777 
778 	/* Disable port interrupts */
779 	ahci_pwrite(ap, AHCI_PREG_IE, 0);
780 
781 	/* Sec 10.1.2 - deinitialise port if it is already running */
782 	cmd = ahci_pread(ap, AHCI_PREG_CMD);
783 	if (ISSET(cmd, (AHCI_PREG_CMD_ST | AHCI_PREG_CMD_CR |
784 	    AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_FR)) ||
785 	    ISSET(ahci_pread(ap, AHCI_PREG_SCTL), AHCI_PREG_SCTL_DET)) {
786 		int r;
787 
788 		r = ahci_port_stop(ap, 1);
789 		if (r) {
790 			printf("%s: unable to disable %s, ignoring port %d\n",
791 			    DEVNAME(sc), r == 2 ? "CR" : "FR", port);
792 			rc = ENXIO;
793 			goto reterr;
794 		}
795 
796 		/* Write DET to zero */
797 		ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
798 	}
799 
800 	/* Setup RFIS base address */
801 	ap->ap_rfis = (struct ahci_rfis *) AHCI_DMA_KVA(ap->ap_dmamem_rfis);
802 	dva = AHCI_DMA_DVA(ap->ap_dmamem_rfis);
803 	ahci_pwrite(ap, AHCI_PREG_FBU, (u_int32_t)(dva >> 32));
804 	ahci_pwrite(ap, AHCI_PREG_FB, (u_int32_t)dva);
805 
806 	/* Enable FIS reception and activate port. */
807 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
808 	cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD | AHCI_PREG_CMD_SUD;
809 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_ICC_ACTIVE);
810 
811 	/* Check whether port activated.  Skip it if not. */
812 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
813 	if (!ISSET(cmd, AHCI_PREG_CMD_FRE)) {
814 		rc = ENXIO;
815 		goto reterr;
816 	}
817 
818 	/* Setup command list base address */
819 	dva = AHCI_DMA_DVA(ap->ap_dmamem_cmd_list);
820 	ahci_pwrite(ap, AHCI_PREG_CLBU, (u_int32_t)(dva >> 32));
821 	ahci_pwrite(ap, AHCI_PREG_CLB, (u_int32_t)dva);
822 
823 	/* Wait for ICC change to complete */
824 	ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC, 1);
825 
826 	/* Reset port */
827 	rc = ahci_port_portreset(ap, 1);
828 	switch (rc) {
829 	case ENODEV:
830 		switch (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
831 		case AHCI_PREG_SSTS_DET_DEV_NE:
832 			printf("%s: device not communicating on port %d\n",
833 			    DEVNAME(sc), port);
834 			break;
835 		case AHCI_PREG_SSTS_DET_PHYOFFLINE:
836 			printf("%s: PHY offline on port %d\n", DEVNAME(sc),
837 			    port);
838 			break;
839 		default:
840 			DPRINTF(AHCI_D_VERBOSE, "%s: no device detected "
841 			    "on port %d\n", DEVNAME(sc), port);
842 			break;
843 		}
844 		goto reterr;
845 
846 	case EBUSY:
847 		printf("%s: device on port %d didn't come ready, "
848 		    "TFD: 0x%b\n", DEVNAME(sc), port,
849 		    ahci_pread(ap, AHCI_PREG_TFD), AHCI_PFMT_TFD_STS);
850 
851 		/* Try a soft reset to clear busy */
852 		rc = ahci_port_softreset(ap);
853 		if (rc) {
854 			printf("%s: unable to communicate "
855 			    "with device on port %d\n", DEVNAME(sc), port);
856 			goto reterr;
857 		}
858 		break;
859 
860 	default:
861 		break;
862 	}
863 	DPRINTF(AHCI_D_VERBOSE, "%s: detected device on port %d\n",
864 	    DEVNAME(sc), port);
865 
866 	if (ap->ap_pmp_ports > 0) {
867 		int p;
868 
869 		for (p = 0; p < ap->ap_pmp_ports; p++) {
870 			int sig;
871 
872 			/* might need to do a portreset first here? */
873 
874 			/* softreset the port */
875 			if (ahci_pmp_port_softreset(ap, p)) {
876 				printf("%s.%d: unable to probe PMP port due to"
877 				    " softreset failure\n", PORTNAME(ap), p);
878 				continue;
879 			}
880 
881 			sig = ahci_port_signature(ap);
882 			printf("%s.%d: port signature returned %d\n",
883 			    PORTNAME(ap), p, sig);
884 		}
885 	}
886 
887 	/* Enable command transfers on port */
888 	if (ahci_port_start(ap, 0)) {
889 		printf("%s: failed to start command DMA on port %d, "
890 		    "disabling\n", DEVNAME(sc), port);
891 		rc = ENXIO;	/* couldn't start port */
892 	}
893 
894 	/* Flush interrupts for port */
895 	ahci_pwrite(ap, AHCI_PREG_IS, ahci_pread(ap, AHCI_PREG_IS));
896 	ahci_write(sc, AHCI_REG_IS, 1 << port);
897 
898 	ahci_enable_interrupts(ap);
899 
900 reterr:
901 	return (rc);
902 }
903 
904 int
905 ahci_default_port_start(struct ahci_port *ap, int fre_only)
906 {
907 	u_int32_t			r;
908 
909 	/* Turn on FRE (and ST) */
910 	r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
911 	r |= AHCI_PREG_CMD_FRE;
912 	if (!fre_only)
913 		r |= AHCI_PREG_CMD_ST;
914 	ahci_pwrite(ap, AHCI_PREG_CMD, r);
915 
916 #ifdef AHCI_COALESCE
917 	/* (Re-)enable coalescing on the port. */
918 	if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
919 		ap->ap_sc->sc_ccc_ports_cur |= (1 << ap->ap_num);
920 		ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
921 		    ap->ap_sc->sc_ccc_ports_cur);
922 	}
923 #endif
924 
925 	return (0);
926 }
927 
928 int
929 ahci_port_stop(struct ahci_port *ap, int stop_fis_rx)
930 {
931 	u_int32_t			r;
932 
933 #ifdef AHCI_COALESCE
934 	/* Disable coalescing on the port while it is stopped. */
935 	if (ap->ap_sc->sc_ccc_ports & (1 << ap->ap_num)) {
936 		ap->ap_sc->sc_ccc_ports_cur &= ~(1 << ap->ap_num);
937 		ahci_write(ap->ap_sc, AHCI_REG_CCC_PORTS,
938 		    ap->ap_sc->sc_ccc_ports_cur);
939 	}
940 #endif
941 
942 	/* Turn off ST (and FRE) */
943 	r = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
944 	r &= ~AHCI_PREG_CMD_ST;
945 	if (stop_fis_rx)
946 		r &= ~AHCI_PREG_CMD_FRE;
947 	ahci_pwrite(ap, AHCI_PREG_CMD, r);
948 
949 	/* Wait for CR to go off */
950 	if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CR, 1))
951 		return (1);
952 
953 	/* Wait for FR to go off */
954 	if (stop_fis_rx &&
955 	    ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_FR, 1))
956 		return (2);
957 
958 	return (0);
959 }
960 
961 /* AHCI command list override -> forcibly clear TFD.STS.{BSY,DRQ} */
962 int
963 ahci_port_clo(struct ahci_port *ap)
964 {
965 	struct ahci_softc		*sc = ap->ap_sc;
966 	u_int32_t			cmd;
967 
968 	/* Only attempt CLO if supported by controller */
969 	if (!ISSET(ahci_read(sc, AHCI_REG_CAP), AHCI_REG_CAP_SCLO))
970 		return (1);
971 
972 	/* Issue CLO */
973 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
974 #ifdef DIAGNOSTIC
975 	if (ISSET(cmd, AHCI_PREG_CMD_ST))
976 		printf("%s: CLO requested while port running\n", PORTNAME(ap));
977 #endif
978 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd | AHCI_PREG_CMD_CLO);
979 
980 	/* Wait for completion */
981 	if (ahci_pwait_clr(ap, AHCI_PREG_CMD, AHCI_PREG_CMD_CLO, 1)) {
982 		printf("%s: CLO did not complete\n", PORTNAME(ap));
983 		return (1);
984 	}
985 
986 	return (0);
987 }
988 
989 /* AHCI soft reset, Section 10.4.1 */
990 int
991 ahci_port_softreset(struct ahci_port *ap)
992 {
993 	struct ahci_ccb			*ccb = NULL;
994 	struct ahci_cmd_hdr		*cmd_slot;
995 	u_int8_t			*fis;
996 	int				s, rc = EIO, oldstate;
997 	u_int32_t			cmd;
998 
999 	DPRINTF(AHCI_D_VERBOSE, "%s: soft reset\n", PORTNAME(ap));
1000 
1001 	s = splbio();
1002 	oldstate = ap->ap_state;
1003 	ap->ap_state = AP_S_ERROR_RECOVERY;
1004 
1005 	/* Save previous command register state */
1006 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1007 
1008 	/* Idle port */
1009 	if (ahci_port_stop(ap, 0)) {
1010 		printf("%s: failed to stop port, cannot softreset\n",
1011 		    PORTNAME(ap));
1012 		goto err;
1013 	}
1014 
1015 	/* Request CLO if device appears hung */
1016 	if (ISSET(ahci_pread(ap, AHCI_PREG_TFD), AHCI_PREG_TFD_STS_BSY |
1017 	    AHCI_PREG_TFD_STS_DRQ))
1018 		ahci_port_clo(ap);
1019 
1020 	/* Clear port errors to permit TFD transfer */
1021 	ahci_pwrite(ap, AHCI_PREG_SERR, ahci_pread(ap, AHCI_PREG_SERR));
1022 
1023 	/* Restart port */
1024 	if (ahci_port_start(ap, 0)) {
1025 		printf("%s: failed to start port, cannot softreset\n",
1026 		    PORTNAME(ap));
1027 		goto err;
1028 	}
1029 
1030 	/* Check whether CLO worked */
1031 	if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1032 	    AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ, 1)) {
1033 		printf("%s: CLO %s, need port reset\n", PORTNAME(ap),
1034 		    ISSET(ahci_read(ap->ap_sc, AHCI_REG_CAP), AHCI_REG_CAP_SCLO)
1035 		    ? "failed" : "unsupported");
1036 		rc = EBUSY;
1037 		goto err;
1038 	}
1039 
1040 	/* Prep first D2H command with SRST feature & clear busy/reset flags */
1041 	ccb = ahci_get_err_ccb(ap);
1042 	cmd_slot = ccb->ccb_cmd_hdr;
1043 	memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
1044 
1045 	fis = ccb->ccb_cmd_table->cfis;
1046 	fis[0] = ATA_FIS_TYPE_H2D;
1047 	fis[15] = ATA_FIS_CONTROL_SRST;
1048 
1049 	cmd_slot->prdtl = 0;
1050 	htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
1051 	    AHCI_CMD_LIST_FLAG_C | AHCI_CMD_LIST_FLAG_R |
1052 	    AHCI_CMD_LIST_FLAG_W);
1053 
1054 	ccb->ccb_xa.state = ATA_S_PENDING;
1055 	if (ahci_poll(ccb, 1000, NULL) != 0)
1056 		goto err;
1057 
1058 	/* Prep second D2H command to read status and complete reset sequence */
1059 	fis[0] = ATA_FIS_TYPE_H2D;
1060 	fis[15] = 0;
1061 
1062 	cmd_slot->prdtl = 0;
1063 	htolem16(&cmd_slot->flags, 5 | AHCI_CMD_LIST_FLAG_W);
1064 
1065 	ccb->ccb_xa.state = ATA_S_PENDING;
1066 	if (ahci_poll(ccb, 1000, NULL) != 0)
1067 		goto err;
1068 
1069 	if (ahci_pwait_clr(ap, AHCI_PREG_TFD, AHCI_PREG_TFD_STS_BSY |
1070 	    AHCI_PREG_TFD_STS_DRQ | AHCI_PREG_TFD_STS_ERR, 1)) {
1071 		printf("%s: device didn't come ready after reset, TFD: 0x%b\n",
1072 		    PORTNAME(ap), ahci_pread(ap, AHCI_PREG_TFD),
1073 		    AHCI_PFMT_TFD_STS);
1074 		rc = EBUSY;
1075 		goto err;
1076 	}
1077 
1078 	rc = 0;
1079 err:
1080 	if (ccb != NULL) {
1081 		/* Abort our command, if it failed, by stopping command DMA. */
1082 		if (rc != 0 && ISSET(ap->ap_active, 1 << ccb->ccb_slot)) {
1083 			printf("%s: stopping the port, softreset slot %d was "
1084 			    "still active.\n", PORTNAME(ap), ccb->ccb_slot);
1085 			ahci_port_stop(ap, 0);
1086 		}
1087 		ccb->ccb_xa.state = ATA_S_ERROR;
1088 		ahci_put_err_ccb(ccb);
1089 	}
1090 
1091 	/* Restore saved CMD register state */
1092 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1093 	ap->ap_state = oldstate;
1094 
1095 	splx(s);
1096 
1097 	return (rc);
1098 }
1099 
1100 int
1101 ahci_pmp_port_softreset(struct ahci_port *ap, int pmp_port)
1102 {
1103 	struct ahci_ccb		*ccb = NULL;
1104 	u_int32_t		data;
1105 	int			count;
1106 	int			rc;
1107 	int			s;
1108 	struct ahci_cmd_hdr	*cmd_slot;
1109 	u_int8_t		*fis;
1110 
1111 	s = splbio();
1112 	/* ignore spurious IFS errors while resetting */
1113 	DPRINTF(AHCI_D_VERBOSE, "%s: now ignoring IFS\n", PORTNAME(ap));
1114 	ap->ap_pmp_ignore_ifs = 1;
1115 
1116 	count = 2;
1117 	rc = 0;
1118 	do {
1119 		if (ccb != NULL) {
1120 			ahci_put_pmp_ccb(ccb);
1121 			ccb = NULL;
1122 		}
1123 
1124 		if (ahci_pmp_phy_status(ap, pmp_port, &data)) {
1125 			printf("%s.%d: unable to clear PHY status\n",
1126 			    PORTNAME(ap), pmp_port);
1127 		}
1128 		ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1129 		/* maybe don't do this on the first loop: */
1130 		ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
1131 		ahci_pmp_write(ap, pmp_port, SATA_PMREG_SERR, -1);
1132 
1133 		/* send first softreset FIS */
1134 		ccb = ahci_get_pmp_ccb(ap);
1135 		cmd_slot = ccb->ccb_cmd_hdr;
1136 		memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
1137 
1138 		fis = ccb->ccb_cmd_table->cfis;
1139 		fis[0] = ATA_FIS_TYPE_H2D;
1140 		fis[1] = pmp_port;
1141 		fis[15] = ATA_FIS_CONTROL_SRST | ATA_FIS_CONTROL_4BIT;
1142 
1143 		cmd_slot->prdtl = 0;
1144 		htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
1145 		    AHCI_CMD_LIST_FLAG_C | AHCI_CMD_LIST_FLAG_R |
1146 		    (pmp_port << AHCI_CMD_LIST_FLAG_PMP_SHIFT));
1147 
1148 		ccb->ccb_xa.state = ATA_S_PENDING;
1149 
1150 		DPRINTF(AHCI_D_VERBOSE, "%s.%d: sending PMP softreset cmd\n",
1151 		    PORTNAME(ap), pmp_port);
1152 		if (ahci_poll(ccb, 1000, ahci_pmp_probe_timeout) != 0) {
1153 			printf("%s.%d: PMP port softreset cmd failed\n",
1154 			       PORTNAME(ap), pmp_port);
1155 			rc = EBUSY;
1156 			if (count > 0) {
1157 				/* probably delay a while to allow
1158 				 * it to settle down?
1159 				 */
1160 			}
1161 			continue;
1162 		}
1163 
1164 		/* send signature FIS */
1165 		memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
1166 		fis[0] = ATA_FIS_TYPE_H2D;
1167 		fis[1] = pmp_port;
1168 		fis[15] = ATA_FIS_CONTROL_4BIT;
1169 
1170 		cmd_slot->prdtl = 0;
1171 		htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
1172 		    (pmp_port << AHCI_CMD_LIST_FLAG_PMP_SHIFT));
1173 
1174 		DPRINTF(AHCI_D_VERBOSE, "%s.%d: sending PMP probe status cmd\n",
1175 		    PORTNAME(ap), pmp_port);
1176 		ccb->ccb_xa.state = ATA_S_PENDING;
1177 		if (ahci_poll(ccb, 5000, ahci_pmp_probe_timeout) != 0) {
1178 			DPRINTF(AHCI_D_VERBOSE, "%s.%d: PMP probe status cmd "
1179 			    "failed\n", PORTNAME(ap), pmp_port);
1180 			rc = EBUSY;
1181 			if (count > 0) {
1182 				/* sleep a while? */
1183 			}
1184 			continue;
1185 		}
1186 
1187 		fis[15] = 0;
1188 		break;
1189 	} while (count--);
1190 
1191 	if (ccb != NULL) {
1192 		ahci_put_pmp_ccb(ccb);
1193 		ccb = NULL;
1194 	}
1195 
1196 	/* clean up a bit */
1197 	ahci_pmp_write(ap, pmp_port, SATA_PMREG_SERR, -1);
1198 	ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1199 	ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
1200 	ap->ap_pmp_ignore_ifs = 0;
1201 	DPRINTF(AHCI_D_VERBOSE, "%s: no longer ignoring IFS\n", PORTNAME(ap));
1202 	splx(s);
1203 
1204 	return (rc);
1205 }
1206 
1207 int
1208 ahci_pmp_port_probe(struct ahci_port *ap, int pmp_port)
1209 {
1210 	int sig;
1211 
1212 	ap->ap_state = AP_S_PMP_PORT_PROBE;
1213 
1214 	DPRINTF(AHCI_D_VERBOSE, "%s.%d: probing pmp port\n", PORTNAME(ap),
1215 	    pmp_port);
1216 	if (ahci_pmp_port_portreset(ap, pmp_port)) {
1217 		printf("%s.%d: unable to probe PMP port; portreset failed\n",
1218 		    PORTNAME(ap), pmp_port);
1219 		ap->ap_state = AP_S_NORMAL;
1220 		return (ATA_PORT_T_NONE);
1221 	}
1222 
1223 	if (ahci_pmp_port_softreset(ap, pmp_port)) {
1224 		printf("%s.%d: unable to probe PMP port due to softreset "
1225 		    "failure\n", PORTNAME(ap), pmp_port);
1226 		ap->ap_state = AP_S_NORMAL;
1227 		return (ATA_PORT_T_NONE);
1228 	}
1229 
1230 	sig = ahci_port_signature(ap);
1231 	DPRINTF(AHCI_D_VERBOSE, "%s.%d: port signature returned %d\n",
1232 	    PORTNAME(ap), pmp_port, sig);
1233 	ap->ap_state = AP_S_NORMAL;
1234 	return (sig);
1235 }
1236 
1237 
1238 void
1239 ahci_flush_tfd(struct ahci_port *ap)
1240 {
1241 	u_int32_t r;
1242 
1243 	r = ahci_pread(ap, AHCI_PREG_SERR);
1244 	if (r & AHCI_PREG_SERR_DIAG_X)
1245 		ahci_pwrite(ap, AHCI_PREG_SERR, AHCI_PREG_SERR_DIAG_X);
1246 }
1247 
1248 u_int32_t
1249 ahci_active_mask(struct ahci_port *ap)
1250 {
1251 	u_int32_t mask;
1252 
1253 	mask = ahci_pread(ap, AHCI_PREG_CI);
1254 	if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SNCQ)
1255 		mask |= ahci_pread(ap, AHCI_PREG_SACT);
1256 	return mask;
1257 }
1258 
1259 void
1260 ahci_pmp_probe_timeout(void *cookie)
1261 {
1262 	struct ahci_ccb *ccb = cookie;
1263 	struct ahci_port *ap = ccb->ccb_port;
1264 	u_int32_t mask;
1265 
1266 	DPRINTF(AHCI_D_VERBOSE, "%s: PMP probe cmd timed out\n", PORTNAME(ap));
1267 	switch (ccb->ccb_xa.state) {
1268 	case ATA_S_PENDING:
1269 		TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
1270 		ccb->ccb_xa.state = ATA_S_TIMEOUT;
1271 		break;
1272 
1273 	case ATA_S_ONCHIP:
1274 	case ATA_S_ERROR:  /* currently mostly here for the ATI SBx00 quirk */
1275 		/* clear the command on-chip */
1276 		KASSERT(ap->ap_active == (1 << ccb->ccb_slot) &&
1277 		    ap->ap_sactive == 0);
1278 		ahci_port_stop(ap, 0);
1279 		ahci_port_start(ap, 0);
1280 
1281 		if (ahci_active_mask(ap) != 0) {
1282 			ahci_port_stop(ap, 0);
1283 			ahci_port_start(ap, 0);
1284 			mask = ahci_active_mask(ap);
1285 			if (mask != 0) {
1286 				printf("%s: ahci_pmp_probe_timeout: failed to "
1287 				    "clear active cmds: %08x\n", PORTNAME(ap),
1288 				    mask);
1289 			}
1290 		}
1291 
1292 		ccb->ccb_xa.state = ATA_S_TIMEOUT;
1293 		ap->ap_active &= ~(1 << ccb->ccb_slot);
1294 		KASSERT(ap->ap_active_cnt > 0);
1295 		--ap->ap_active_cnt;
1296 		DPRINTF(AHCI_D_VERBOSE, "%s: timed out %d, active %x, count %d\n",
1297 		    PORTNAME(ap), ccb->ccb_slot, ap->ap_active, ap->ap_active_cnt);
1298 		break;
1299 
1300 	default:
1301 		panic("%s: ahci_pmp_probe_timeout: ccb in bad state %d",
1302 			PORTNAME(ap), ccb->ccb_xa.state);
1303 	}
1304 }
1305 
1306 int
1307 ahci_port_signature(struct ahci_port *ap)
1308 {
1309 	u_int32_t sig;
1310 
1311 	sig = ahci_pread(ap, AHCI_PREG_SIG);
1312 	if ((sig & 0xffff0000) == (SATA_SIGNATURE_ATAPI & 0xffff0000))
1313 		return (ATA_PORT_T_ATAPI);
1314 	else if ((sig & 0xffff0000) == (SATA_SIGNATURE_PORT_MULTIPLIER &
1315 	    0xffff0000))
1316 		return (ATA_PORT_T_PM);
1317 	else
1318 		return (ATA_PORT_T_DISK);
1319 }
1320 
1321 int
1322 ahci_pmp_port_portreset(struct ahci_port *ap, int pmp_port)
1323 {
1324 	u_int32_t cmd, data;
1325 	int loop;
1326 	int rc = 1;
1327 	int s;
1328 
1329 	s = splbio();
1330 	DPRINTF(AHCI_D_VERBOSE, "%s.%d: PMP port reset\n", PORTNAME(ap),
1331 	    pmp_port);
1332 
1333 	/* Save previous command register state */
1334 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1335 
1336 	/* turn off power management and disable the PHY */
1337 	data = AHCI_PREG_SCTL_IPM_DISABLED;
1338 	/* maybe add AHCI_PREG_SCTL_DET_DISABLE */
1339 	if (ahci_pmp_write(ap, pmp_port, SATA_PMREG_SERR, -1))
1340 		goto err;
1341 	if (ahci_pmp_write(ap, pmp_port, SATA_PMREG_SCTL, data))
1342 		goto err;
1343 	delay(10000);
1344 
1345 	/* start COMRESET */
1346 	data = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
1347 	if ((ap->ap_sc->sc_dev.dv_cfdata->cf_flags & 0x01) != 0) {
1348 		DPRINTF(AHCI_D_VERBOSE, "%s.%d: forcing GEN1\n", PORTNAME(ap),
1349 		    pmp_port);
1350 		data |= AHCI_PREG_SCTL_SPD_GEN1;
1351 	} else
1352 		data |= AHCI_PREG_SCTL_SPD_ANY;
1353 
1354 	if (ahci_pmp_write(ap, pmp_port, SATA_PMREG_SCTL, data))
1355 		goto err;
1356 
1357 	/* give it a while to settle down */
1358 	delay(100000);
1359 
1360 	if (ahci_pmp_phy_status(ap, pmp_port, &data)) {
1361 		printf("%s.%d: cannot clear PHY status\n", PORTNAME(ap),
1362 		    pmp_port);
1363 	}
1364 
1365 	/* start trying to negotiate */
1366 	ahci_pmp_write(ap, pmp_port, SATA_PMREG_SERR, -1);
1367 	data = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_NONE;
1368 	if (ahci_pmp_write(ap, pmp_port, SATA_PMREG_SCTL, data))
1369 		goto err;
1370 
1371 	/* give it a while to detect */
1372 	for (loop = 3; loop; --loop) {
1373 		if (ahci_pmp_read(ap, pmp_port, SATA_PMREG_SSTS, &data))
1374 			goto err;
1375 		if (data & AHCI_PREG_SSTS_DET)
1376 			break;
1377 		delay(100000);
1378 	}
1379 	if (loop == 0) {
1380 		printf("%s.%d: port is unplugged\n", PORTNAME(ap), pmp_port);
1381 		goto err;
1382 	}
1383 
1384 	/* give it even longer to fully negotiate */
1385 	for (loop = 30; loop; --loop) {
1386 		if (ahci_pmp_read(ap, pmp_port, SATA_PMREG_SSTS, &data))
1387 			goto err;
1388 		if ((data & AHCI_PREG_SSTS_DET) == AHCI_PREG_SSTS_DET_DEV)
1389 			break;
1390 		delay(100000);
1391 	}
1392 
1393 	if (loop == 0) {
1394 		printf("%s.%d: device is not negotiating\n", PORTNAME(ap),
1395 		    pmp_port);
1396 		goto err;
1397 	}
1398 
1399 	/* device detected */
1400 	DPRINTF(AHCI_D_VERBOSE, "%s.%d: device detected\n", PORTNAME(ap),
1401 	    pmp_port);
1402 
1403 	/* clean up a bit */
1404 	delay(100000);
1405 	ahci_pmp_write(ap, pmp_port, SATA_PMREG_SERR, -1);
1406 	ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1407 	ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
1408 
1409 	rc = 0;
1410 err:
1411 	/* Restore preserved port state */
1412 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1413 	splx(s);
1414 	return (rc);
1415 }
1416 
1417 /* AHCI port reset, Section 10.4.2 */
1418 
1419 void
1420 ahci_port_comreset(struct ahci_port *ap)
1421 {
1422 	u_int32_t			r;
1423 
1424 	r = AHCI_PREG_SCTL_IPM_DISABLED | AHCI_PREG_SCTL_DET_INIT;
1425 	if ((ap->ap_sc->sc_dev.dv_cfdata->cf_flags & 0x01) != 0) {
1426 		DPRINTF(AHCI_D_VERBOSE, "%s: forcing GEN1\n", PORTNAME(ap));
1427 		r |= AHCI_PREG_SCTL_SPD_GEN1;
1428 	} else
1429 		r |= AHCI_PREG_SCTL_SPD_ANY;
1430 	ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1431 	delay(10000);	/* wait at least 1ms for COMRESET to be sent */
1432 	r &= ~AHCI_PREG_SCTL_DET_INIT;
1433 	r |= AHCI_PREG_SCTL_DET_NONE;
1434 	ahci_pwrite(ap, AHCI_PREG_SCTL, r);
1435 	delay(10000);
1436 }
1437 
1438 void
1439 ahci_port_portreset_start(struct ahci_port *ap)
1440 {
1441 	int				s;
1442 
1443 	s = splbio();
1444 	DPRINTF(AHCI_D_VERBOSE, "%s: port reset\n", PORTNAME(ap));
1445 
1446 	/* Save previous command register state */
1447 	ap->ap_saved_cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1448 
1449 	/* Clear ST, ignoring failure */
1450 	ahci_port_stop(ap, 0);
1451 
1452 	/* Perform device detection */
1453 	ahci_pwrite(ap, AHCI_PREG_SCTL, 0);
1454 	delay(10000);
1455 	ahci_port_comreset(ap);
1456 	splx(s);
1457 }
1458 
1459 int
1460 ahci_port_portreset_poll(struct ahci_port *ap)
1461 {
1462 	if ((ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) !=
1463 	    AHCI_PREG_SSTS_DET_DEV)
1464 		return (EAGAIN);
1465 	return (0);
1466 }
1467 
1468 void
1469 ahci_port_portreset_wait(struct ahci_port *ap)
1470 {
1471 	int				i;
1472 
1473 	for (i = 0; i < 1000; i++) {
1474 		if (ahci_port_portreset_poll(ap) == 0)
1475 			break;
1476 		delay(1000);
1477 	}
1478 }
1479 
1480 int
1481 ahci_port_portreset_finish(struct ahci_port *ap, int pmp)
1482 {
1483 	int				rc, s, retries = 0;
1484 
1485 	s = splbio();
1486 retry:
1487 	if (ahci_port_portreset_poll(ap)) {
1488 		rc = ENODEV;
1489 		if (ahci_pread(ap, AHCI_PREG_SSTS) & AHCI_PREG_SSTS_DET) {
1490 			/* this may be a port multiplier with no device
1491 			 * on port 0, so still do the pmp check if requested.
1492 			 */
1493 		} else {
1494 			goto err;
1495 		}
1496 	} else {
1497 		/* Clear SERR (incl X bit), so TFD can update */
1498 		ahci_pwrite(ap, AHCI_PREG_SERR, ahci_pread(ap, AHCI_PREG_SERR));
1499 
1500 		/* Wait for device to become ready */
1501 		if (ahci_pwait_clr(ap, AHCI_PREG_TFD, AHCI_PREG_TFD_STS_BSY |
1502 		    AHCI_PREG_TFD_STS_DRQ | AHCI_PREG_TFD_STS_ERR, 3)) {
1503 			/* even if the device doesn't wake up, check if there's
1504 			 * a port multiplier there
1505 			 */
1506 			if (retries == 0) {
1507 				retries = 1;
1508 				ahci_port_comreset(ap);
1509 				ahci_port_portreset_wait(ap);
1510 				goto retry;
1511 			}
1512 			rc = EBUSY;
1513 		} else {
1514 			rc = 0;
1515 		}
1516 	}
1517 
1518 	if (pmp != 0) {
1519 		if (ahci_port_detect_pmp(ap)) {
1520 			/* reset again without pmp support */
1521 			pmp = 0;
1522 			retries = 0;
1523 			ahci_port_comreset(ap);
1524 			ahci_port_portreset_wait(ap);
1525 			goto retry;
1526 		}
1527 	}
1528 
1529 err:
1530 	/* Restore preserved port state */
1531 	ahci_pwrite(ap, AHCI_PREG_CMD, ap->ap_saved_cmd);
1532 	ap->ap_saved_cmd = 0;
1533 	splx(s);
1534 
1535 	return (rc);
1536 }
1537 
1538 int
1539 ahci_port_portreset(struct ahci_port *ap, int pmp)
1540 {
1541 	ahci_port_portreset_start(ap);
1542 	ahci_port_portreset_wait(ap);
1543 	return (ahci_port_portreset_finish(ap, pmp));
1544 }
1545 
1546 int
1547 ahci_port_detect_pmp(struct ahci_port *ap)
1548 {
1549 	int				 count, pmp_rc, rc;
1550 	u_int32_t			 r, cmd;
1551 	struct ahci_cmd_hdr		*cmd_slot;
1552 	struct ahci_ccb			*ccb = NULL;
1553 	u_int8_t			*fis = NULL;
1554 
1555 	if ((ap->ap_sc->sc_flags & AHCI_F_NO_PMP) ||
1556 	    !ISSET(ahci_read(ap->ap_sc, AHCI_REG_CAP), AHCI_REG_CAP_SPM)) {
1557 		return 0;
1558 	}
1559 
1560 	rc = 0;
1561 	pmp_rc = 0;
1562 	count = 2;
1563 	do {
1564 		DPRINTF(AHCI_D_VERBOSE, "%s: PMP probe %d\n", PORTNAME(ap),
1565 		    count);
1566 		if (ccb != NULL) {
1567 			ahci_put_pmp_ccb(ccb);
1568 			ccb = NULL;
1569 		}
1570 		ahci_port_stop(ap, 0);
1571 		ap->ap_state = AP_S_PMP_PROBE;
1572 
1573 		/* set PMA in cmd reg */
1574 		cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1575 		if ((cmd & AHCI_PREG_CMD_PMA) == 0) {
1576 			cmd |= AHCI_PREG_CMD_PMA;
1577 			ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1578 		}
1579 
1580 		/* Flush errors and request CLO unconditionally,
1581 		 * then start the port
1582 		 */
1583 		r = ahci_pread(ap, AHCI_PREG_SERR);
1584 		if (r & AHCI_PREG_SERR_DIAG_X)
1585 			ahci_pwrite(ap, AHCI_PREG_SERR,
1586 			    AHCI_PREG_SERR_DIAG_X);
1587 
1588 		/* Request CLO */
1589 		ahci_port_clo(ap);
1590 
1591 		/* Clear port errors to permit TFD transfer */
1592 		r = ahci_pread(ap, AHCI_PREG_SERR);
1593 		ahci_pwrite(ap, AHCI_PREG_SERR, r);
1594 
1595 		/* Restart port */
1596 		if (ahci_port_start(ap, 0)) {
1597 			rc = EBUSY;
1598 			printf("%s: failed to start port, cannot probe PMP\n",
1599 			    PORTNAME(ap));
1600 			break;
1601 		}
1602 
1603 		/* Check whether CLO worked */
1604 		if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1605 		    AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ, 1)) {
1606 			u_int32_t cap;
1607 
1608 			cap = ahci_read(ap->ap_sc, AHCI_REG_CAP);
1609 			printf("%s: CLO %s, need port reset\n",
1610 			    PORTNAME(ap),
1611 			    ISSET(cap, AHCI_REG_CAP_SCLO)
1612 			    ? "failed" : "unsupported");
1613 			pmp_rc = EBUSY;
1614 			break;
1615 		}
1616 
1617 		/* Prep first command with SRST feature &
1618 		 * clear busy/reset flags
1619 		 */
1620 		ccb = ahci_get_pmp_ccb(ap);
1621 		cmd_slot = ccb->ccb_cmd_hdr;
1622 		memset(ccb->ccb_cmd_table, 0,
1623 		    sizeof(struct ahci_cmd_table));
1624 
1625 		fis = ccb->ccb_cmd_table->cfis;
1626 		fis[0] = ATA_FIS_TYPE_H2D;
1627 		fis[1] = SATA_PMP_CONTROL_PORT;
1628 		fis[15] = ATA_FIS_CONTROL_SRST | ATA_FIS_CONTROL_4BIT;
1629 
1630 		cmd_slot->prdtl = 0;
1631 		htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
1632 		    AHCI_CMD_LIST_FLAG_C | AHCI_CMD_LIST_FLAG_R |
1633 		    AHCI_CMD_LIST_FLAG_PMP);
1634 
1635 		DPRINTF(AHCI_D_VERBOSE, "%s: sending PMP reset cmd\n",
1636 		    PORTNAME(ap));
1637 		ccb->ccb_xa.state = ATA_S_PENDING;
1638 		if (ahci_poll(ccb, 1000, ahci_pmp_probe_timeout) != 0) {
1639 			DPRINTF(AHCI_D_VERBOSE, "%s: PMP reset cmd failed\n",
1640 			    PORTNAME(ap));
1641 			pmp_rc = EBUSY;
1642 			continue;
1643 		}
1644 
1645 		if (ahci_pwait_clr(ap, AHCI_PREG_TFD,
1646 		    AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ, 1)) {
1647 			printf("%s: port busy after first PMP probe FIS\n",
1648 			    PORTNAME(ap));
1649 		}
1650 
1651 		/* clear errors in case the device
1652 		 * didn't reset cleanly
1653 		 */
1654 		ahci_flush_tfd(ap);
1655 		r = ahci_pread(ap, AHCI_PREG_SERR);
1656 		ahci_pwrite(ap, AHCI_PREG_SERR, r);
1657 
1658 		/* Prep second command to read status and
1659 		 * complete reset sequence
1660 		 */
1661 		memset(ccb->ccb_cmd_table, 0,
1662 		    sizeof(struct ahci_cmd_table));
1663 		fis[0] = ATA_FIS_TYPE_H2D;
1664 		fis[1] = SATA_PMP_CONTROL_PORT;
1665 		fis[15] = ATA_FIS_CONTROL_4BIT;
1666 
1667 		cmd_slot->prdtl = 0;
1668 		htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
1669 		    AHCI_CMD_LIST_FLAG_PMP);
1670 
1671 		DPRINTF(AHCI_D_VERBOSE, "%s: sending PMP probe status cmd\n",
1672 		    PORTNAME(ap));
1673 		ccb->ccb_xa.state = ATA_S_PENDING;
1674 		if (ahci_poll(ccb, 5000, ahci_pmp_probe_timeout) != 0) {
1675 			DPRINTF(AHCI_D_VERBOSE, "%s: PMP probe status "
1676 			    "cmd failed\n", PORTNAME(ap));
1677 			pmp_rc = EBUSY;
1678 			continue;
1679 		}
1680 
1681 		/* apparently we need to retry at least once
1682 		 * to get the right signature
1683 		 */
1684 		fis[15] = 0;
1685 		pmp_rc = 0;
1686 	} while (--count);
1687 
1688 	if (ccb != NULL) {
1689 		ahci_put_pmp_ccb(ccb);
1690 		ccb = NULL;
1691 	}
1692 
1693 	if (ap->ap_state == AP_S_PMP_PROBE) {
1694 		ap->ap_state = AP_S_NORMAL;
1695 	}
1696 
1697 	if (pmp_rc == 0) {
1698 		if (ahci_port_signature(ap) != ATA_PORT_T_PM) {
1699 			DPRINTF(AHCI_D_VERBOSE, "%s: device is not a PMP\n",
1700 			    PORTNAME(ap));
1701 			pmp_rc = EBUSY;
1702 		} else {
1703 			DPRINTF(AHCI_D_VERBOSE, "%s: PMP found\n",
1704 			    PORTNAME(ap));
1705 		}
1706 	}
1707 
1708 	if (pmp_rc == 0) {
1709 		if (ahci_pmp_identify(ap, &ap->ap_pmp_ports)) {
1710 			pmp_rc = EBUSY;
1711 		} else {
1712 			rc = 0;
1713 		}
1714 	}
1715 
1716 	/* if PMP detection failed, so turn off the PMA bit and
1717 	 * reset the port again
1718 	 */
1719 	if (pmp_rc != 0) {
1720 		DPRINTF(AHCI_D_VERBOSE, "%s: no PMP found, resetting "
1721 		    "the port\n", PORTNAME(ap));
1722 		ahci_port_stop(ap, 0);
1723 		ahci_port_clo(ap);
1724 		cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
1725 		cmd &= ~AHCI_PREG_CMD_PMA;
1726 		ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
1727 
1728 		ahci_pwrite(ap, AHCI_PREG_IE, 0);
1729 		ahci_port_stop(ap, 0);
1730 		if (ap->ap_sc->sc_cap & AHCI_REG_CAP_SSNTF)
1731 			ahci_pwrite(ap, AHCI_PREG_SNTF, -1);
1732 		ahci_flush_tfd(ap);
1733 		ahci_pwrite(ap, AHCI_PREG_SERR, -1);
1734 
1735 		ahci_pwrite(ap, AHCI_PREG_IS, -1);
1736 
1737 		ahci_enable_interrupts(ap);
1738 
1739 		rc = pmp_rc;
1740 	}
1741 
1742 	return (rc);
1743 }
1744 
1745 void
1746 ahci_load_prdt_seg(struct ahci_prdt *prd, u_int64_t addr, u_int32_t len,
1747     u_int32_t flags)
1748 {
1749 	flags |= len - 1;
1750 
1751 	htolem64(&prd->dba, addr);
1752 	htolem32(&prd->flags, flags);
1753 }
1754 
1755 int
1756 ahci_load_prdt(struct ahci_ccb *ccb)
1757 {
1758 	struct ahci_port		*ap = ccb->ccb_port;
1759 	struct ahci_softc		*sc = ap->ap_sc;
1760 	struct ata_xfer			*xa = &ccb->ccb_xa;
1761 	struct ahci_prdt		*prdt = ccb->ccb_cmd_table->prdt;
1762 	bus_dmamap_t			dmap = ccb->ccb_dmamap;
1763 	struct ahci_cmd_hdr		*cmd_slot = ccb->ccb_cmd_hdr;
1764 	int				i, error;
1765 
1766 	if (xa->datalen == 0) {
1767 		ccb->ccb_cmd_hdr->prdtl = 0;
1768 		return (0);
1769 	}
1770 
1771 	error = bus_dmamap_load(sc->sc_dmat, dmap, xa->data, xa->datalen, NULL,
1772 	    (xa->flags & ATA_F_NOWAIT) ? BUS_DMA_NOWAIT : BUS_DMA_WAITOK);
1773 	if (error != 0) {
1774 		printf("%s: error %d loading dmamap\n", PORTNAME(ap), error);
1775 		return (1);
1776 	}
1777 
1778 	for (i = 0; i < dmap->dm_nsegs - 1; i++) {
1779 		ahci_load_prdt_seg(&prdt[i], dmap->dm_segs[i].ds_addr,
1780 		    dmap->dm_segs[i].ds_len, 0);
1781 	}
1782 
1783 	ahci_load_prdt_seg(&prdt[i],
1784 	    dmap->dm_segs[i].ds_addr, dmap->dm_segs[i].ds_len,
1785 	    ISSET(xa->flags, ATA_F_PIO) ? AHCI_PRDT_FLAG_INTR : 0);
1786 
1787 	htolem16(&cmd_slot->prdtl, dmap->dm_nsegs);
1788 
1789 	bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
1790 	    (xa->flags & ATA_F_READ) ? BUS_DMASYNC_PREREAD :
1791 	    BUS_DMASYNC_PREWRITE);
1792 
1793 	return (0);
1794 }
1795 
1796 void
1797 ahci_unload_prdt(struct ahci_ccb *ccb)
1798 {
1799 	struct ahci_port		*ap = ccb->ccb_port;
1800 	struct ahci_softc		*sc = ap->ap_sc;
1801 	struct ata_xfer			*xa = &ccb->ccb_xa;
1802 	bus_dmamap_t			dmap = ccb->ccb_dmamap;
1803 
1804 	if (xa->datalen != 0) {
1805 		bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
1806 		    (xa->flags & ATA_F_READ) ? BUS_DMASYNC_POSTREAD :
1807 		    BUS_DMASYNC_POSTWRITE);
1808 
1809 		bus_dmamap_unload(sc->sc_dmat, dmap);
1810 
1811 		if (ccb->ccb_xa.flags & ATA_F_NCQ)
1812 			xa->resid = 0;
1813 		else
1814 			xa->resid = xa->datalen -
1815 			    lemtoh32(&ccb->ccb_cmd_hdr->prdbc);
1816 	}
1817 }
1818 
1819 int
1820 ahci_poll(struct ahci_ccb *ccb, int timeout, void (*timeout_fn)(void *))
1821 {
1822 	struct ahci_port		*ap = ccb->ccb_port;
1823 	int				s;
1824 
1825 	s = splbio();
1826 	ahci_start(ccb);
1827 	do {
1828 		if (ISSET(ahci_port_intr(ap, AHCI_PREG_CI_ALL_SLOTS),
1829 		    1 << ccb->ccb_slot)) {
1830 			splx(s);
1831 			return (0);
1832 		}
1833 		if (ccb->ccb_xa.state == ATA_S_ERROR) {
1834 			DPRINTF(AHCI_D_VERBOSE, "%s: ccb in slot %d errored\n",
1835 			    PORTNAME(ap), ccb->ccb_slot);
1836 			/* pretend it timed out? */
1837 			if (timeout_fn != NULL) {
1838 				timeout_fn(ccb);
1839 			}
1840 			splx(s);
1841 			return (1);
1842 		}
1843 
1844 		delay(1000);
1845 	} while (--timeout > 0);
1846 
1847 	/* Run timeout while at splbio, otherwise ahci_intr could interfere. */
1848 	if (timeout_fn != NULL)
1849 		timeout_fn(ccb);
1850 
1851 	splx(s);
1852 
1853 	return (1);
1854 }
1855 
1856 void
1857 ahci_start(struct ahci_ccb *ccb)
1858 {
1859 	struct ahci_port		*ap = ccb->ccb_port;
1860 	struct ahci_softc		*sc = ap->ap_sc;
1861 
1862 	/* Zero transferred byte count before transfer */
1863 	ccb->ccb_cmd_hdr->prdbc = 0;
1864 
1865 	/* Sync command list entry and corresponding command table entry */
1866 	bus_dmamap_sync(sc->sc_dmat, AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
1867 	    ccb->ccb_slot * sizeof(struct ahci_cmd_hdr),
1868 	    sizeof(struct ahci_cmd_hdr), BUS_DMASYNC_PREWRITE);
1869 	bus_dmamap_sync(sc->sc_dmat, AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
1870 	    ccb->ccb_slot * sizeof(struct ahci_cmd_table),
1871 	    sizeof(struct ahci_cmd_table), BUS_DMASYNC_PREWRITE);
1872 
1873 	/* Prepare RFIS area for write by controller */
1874 	bus_dmamap_sync(sc->sc_dmat, AHCI_DMA_MAP(ap->ap_dmamem_rfis), 0,
1875 	    sizeof(struct ahci_rfis), BUS_DMASYNC_PREREAD);
1876 
1877 	if (ccb->ccb_xa.flags & ATA_F_NCQ) {
1878 		/* Issue NCQ commands only when there are no outstanding
1879 		 * standard commands. */
1880 		if (ap->ap_active != 0 || !TAILQ_EMPTY(&ap->ap_ccb_pending) ||
1881 		    (ap->ap_sactive != 0 &&
1882 		     ap->ap_pmp_ncq_port != ccb->ccb_xa.pmp_port)) {
1883 			TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1884 		} else {
1885 			KASSERT(ap->ap_active_cnt == 0);
1886 			ap->ap_sactive |= (1 << ccb->ccb_slot);
1887 			ccb->ccb_xa.state = ATA_S_ONCHIP;
1888 			ahci_pwrite(ap, AHCI_PREG_SACT, 1 << ccb->ccb_slot);
1889 			ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1890 			ap->ap_pmp_ncq_port = ccb->ccb_xa.pmp_port;
1891 		}
1892 	} else {
1893 		/* Wait for all NCQ commands to finish before issuing standard
1894 		 * command. */
1895 		if (ap->ap_sactive != 0 || ap->ap_active_cnt == 2)
1896 			TAILQ_INSERT_TAIL(&ap->ap_ccb_pending, ccb, ccb_entry);
1897 		else if (ap->ap_active_cnt < 2) {
1898 			ap->ap_active |= 1 << ccb->ccb_slot;
1899 			ccb->ccb_xa.state = ATA_S_ONCHIP;
1900 			ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
1901 			ap->ap_active_cnt++;
1902 		}
1903 	}
1904 }
1905 
1906 void
1907 ahci_issue_pending_ncq_commands(struct ahci_port *ap)
1908 {
1909 	struct ahci_ccb			*nextccb;
1910 	u_int32_t			sact_change = 0;
1911 
1912 	KASSERT(ap->ap_active_cnt == 0);
1913 
1914 	nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1915 	if (nextccb == NULL || !(nextccb->ccb_xa.flags & ATA_F_NCQ))
1916 		return;
1917 
1918 	/* Start all the NCQ commands at the head of the pending list.
1919 	 * If a port multiplier is attached to the port, we can only
1920 	 * issue commands for one of its ports at a time.
1921 	 */
1922 	if (ap->ap_sactive != 0 &&
1923 	    ap->ap_pmp_ncq_port != nextccb->ccb_xa.pmp_port) {
1924 		return;
1925 	}
1926 
1927 	ap->ap_pmp_ncq_port = nextccb->ccb_xa.pmp_port;
1928 	do {
1929 		TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1930 		sact_change |= 1 << nextccb->ccb_slot;
1931 		nextccb->ccb_xa.state = ATA_S_ONCHIP;
1932 		nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1933 	} while (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ) &&
1934 	    (nextccb->ccb_xa.pmp_port == ap->ap_pmp_ncq_port));
1935 
1936 	ap->ap_sactive |= sact_change;
1937 	ahci_pwrite(ap, AHCI_PREG_SACT, sact_change);
1938 	ahci_pwrite(ap, AHCI_PREG_CI, sact_change);
1939 }
1940 
1941 void
1942 ahci_issue_pending_commands(struct ahci_port *ap, int last_was_ncq)
1943 {
1944 	struct ahci_ccb			*nextccb;
1945 
1946 	nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1947 	if (nextccb && (nextccb->ccb_xa.flags & ATA_F_NCQ)) {
1948 		if (last_was_ncq) {
1949 			KASSERT(nextccb->ccb_xa.pmp_port !=
1950 			    ap->ap_pmp_ncq_port);
1951 			/* otherwise it should have been started already */
1952 		} else {
1953 			ap->ap_active_cnt--;
1954 		}
1955 
1956 		/* Issue NCQ commands only when there are no outstanding
1957 		 * standard commands, and previous NCQ commands for other
1958 		 * PMP ports have finished.
1959 		 */
1960 		if (ap->ap_active == 0)
1961 			ahci_issue_pending_ncq_commands(ap);
1962 		else
1963 			KASSERT(ap->ap_active_cnt == 1);
1964 	} else if (nextccb) {
1965 		if (ap->ap_sactive != 0 || last_was_ncq)
1966 			KASSERT(ap->ap_active_cnt == 0);
1967 
1968 		/* Wait for all NCQ commands to finish before issuing standard
1969 		 * command. */
1970 		if (ap->ap_sactive != 0)
1971 			return;
1972 
1973 		/* Keep up to 2 standard commands on-chip at a time. */
1974 		do {
1975 			TAILQ_REMOVE(&ap->ap_ccb_pending, nextccb, ccb_entry);
1976 			ap->ap_active |= 1 << nextccb->ccb_slot;
1977 			nextccb->ccb_xa.state = ATA_S_ONCHIP;
1978 			ahci_pwrite(ap, AHCI_PREG_CI, 1 << nextccb->ccb_slot);
1979 			if (last_was_ncq)
1980 				ap->ap_active_cnt++;
1981 			if (ap->ap_active_cnt == 2)
1982 				break;
1983 			KASSERT(ap->ap_active_cnt == 1);
1984 			nextccb = TAILQ_FIRST(&ap->ap_ccb_pending);
1985 		} while (nextccb && !(nextccb->ccb_xa.flags & ATA_F_NCQ));
1986 	} else if (!last_was_ncq) {
1987 		KASSERT(ap->ap_active_cnt == 1 || ap->ap_active_cnt == 2);
1988 
1989 		/* Standard command finished, none waiting to start. */
1990 		ap->ap_active_cnt--;
1991 	} else {
1992 		KASSERT(ap->ap_active_cnt == 0);
1993 
1994 		/* NCQ command finished. */
1995 	}
1996 }
1997 
1998 int
1999 ahci_intr(void *arg)
2000 {
2001 	struct ahci_softc		*sc = arg;
2002 	u_int32_t			is, ack = 0;
2003 	int				port;
2004 
2005 	/* Read global interrupt status */
2006 	is = ahci_read(sc, AHCI_REG_IS);
2007 	if (is == 0 || is == 0xffffffff)
2008 		return (0);
2009 	ack = is;
2010 
2011 #ifdef AHCI_COALESCE
2012 	/* Check coalescing interrupt first */
2013 	if (is & sc->sc_ccc_mask) {
2014 		DPRINTF(AHCI_D_INTR, "%s: command coalescing interrupt\n",
2015 		    DEVNAME(sc));
2016 		is &= ~sc->sc_ccc_mask;
2017 		is |= sc->sc_ccc_ports_cur;
2018 	}
2019 #endif
2020 
2021 	/* Process interrupts for each port */
2022 	while (is) {
2023 		port = ffs(is) - 1;
2024 		if (sc->sc_ports[port])
2025 			ahci_port_intr(sc->sc_ports[port],
2026 			    AHCI_PREG_CI_ALL_SLOTS);
2027 		is &= ~(1 << port);
2028 	}
2029 
2030 	/* Finally, acknowledge global interrupt */
2031 	ahci_write(sc, AHCI_REG_IS, ack);
2032 
2033 	return (1);
2034 }
2035 
2036 u_int32_t
2037 ahci_port_intr(struct ahci_port *ap, u_int32_t ci_mask)
2038 {
2039 	struct ahci_softc		*sc = ap->ap_sc;
2040 	u_int32_t			is, ci_saved, ci_masked, processed = 0;
2041 	int				slot, need_restart = 0;
2042 	int				process_error = 0;
2043 	struct ahci_ccb			*ccb;
2044 	volatile u_int32_t		*active;
2045 #ifdef DIAGNOSTIC
2046 	u_int32_t			tmp;
2047 #endif
2048 
2049 	is = ahci_pread(ap, AHCI_PREG_IS);
2050 
2051 	/* Ack port interrupt only if checking all command slots. */
2052 	if (ci_mask == AHCI_PREG_CI_ALL_SLOTS)
2053 		ahci_pwrite(ap, AHCI_PREG_IS, is);
2054 
2055 	if (is)
2056 		DPRINTF(AHCI_D_INTR, "%s: interrupt: %b\n", PORTNAME(ap),
2057 		    is, AHCI_PFMT_IS);
2058 
2059 	if (ap->ap_sactive) {
2060 		/* Active NCQ commands - use SActive instead of CI */
2061 		KASSERT(ap->ap_active == 0);
2062 		KASSERT(ap->ap_active_cnt == 0);
2063 		ci_saved = ahci_pread(ap, AHCI_PREG_SACT);
2064 		active = &ap->ap_sactive;
2065 	} else {
2066 		/* Save CI */
2067 		ci_saved = ahci_pread(ap, AHCI_PREG_CI);
2068 		active = &ap->ap_active;
2069 	}
2070 
2071 	if (is & AHCI_PREG_IS_TFES) {
2072 		process_error = 1;
2073 	} else if (is & AHCI_PREG_IS_DHRS) {
2074 		u_int32_t tfd;
2075 		u_int32_t cmd;
2076 		u_int32_t serr;
2077 
2078 		tfd = ahci_pread(ap, AHCI_PREG_TFD);
2079 		cmd = ahci_pread(ap, AHCI_PREG_CMD);
2080 		serr = ahci_pread(ap, AHCI_PREG_SERR);
2081 		if ((tfd & AHCI_PREG_TFD_STS_ERR) &&
2082 		    (cmd & AHCI_PREG_CMD_CR) == 0) {
2083 			DPRINTF(AHCI_D_VERBOSE, "%s: DHRS error, TFD: %b, SERR:"
2084 			    " %b, DIAG: %b\n", PORTNAME(ap), tfd,
2085 			    AHCI_PFMT_TFD_STS, AHCI_PREG_SERR_ERR(serr),
2086 			    AHCI_PFMT_SERR_ERR, AHCI_PREG_SERR_DIAG(serr),
2087 			    AHCI_PFMT_SERR_DIAG);
2088 			process_error = 1;
2089 		} else {
2090 			/* rfis copy back is in the normal execution path */
2091 			ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_DHRS);
2092 		}
2093 	}
2094 
2095 	/* Command failed.  See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2. */
2096 	if (process_error) {
2097 		u_int32_t		tfd, serr;
2098 		int			err_slot;
2099 
2100 		tfd = ahci_pread(ap, AHCI_PREG_TFD);
2101 		serr = ahci_pread(ap, AHCI_PREG_SERR);
2102 
2103 		if (ap->ap_sactive == 0) {
2104 			/* Errored slot is easy to determine from CMD. */
2105 			err_slot = AHCI_PREG_CMD_CCS(ahci_pread(ap,
2106 			    AHCI_PREG_CMD));
2107 
2108 			if ((ci_saved & (1 << err_slot)) == 0) {
2109 				/*
2110 				 * Hardware doesn't seem to report correct
2111 				 * slot number. If there's only one
2112 				 * outstanding command we can cope,
2113 				 * otherwise fail all active commands.
2114 				 */
2115 				if (ap->ap_active_cnt == 1)
2116 					err_slot = ffs(ap->ap_active) - 1;
2117 				else
2118 					goto failall;
2119 			}
2120 
2121 			ccb = &ap->ap_ccbs[err_slot];
2122 
2123 			/* Preserve received taskfile data from the RFIS. */
2124 			memcpy(&ccb->ccb_xa.rfis, ap->ap_rfis->rfis,
2125 			    sizeof(struct ata_fis_d2h));
2126 		} else
2127 			err_slot = -1;	/* Must extract error from log page */
2128 
2129 		DPRINTF(AHCI_D_VERBOSE, "%s: errored slot %d, TFD: %b, SERR:"
2130 		    " %b, DIAG: %b\n", PORTNAME(ap), err_slot, tfd,
2131 		    AHCI_PFMT_TFD_STS, AHCI_PREG_SERR_ERR(serr),
2132 		    AHCI_PFMT_SERR_ERR, AHCI_PREG_SERR_DIAG(serr),
2133 		    AHCI_PFMT_SERR_DIAG);
2134 
2135 		/* Turn off ST to clear CI and SACT. */
2136 		ahci_port_stop(ap, 0);
2137 		need_restart = 1;
2138 
2139 		/* Clear SERR to enable capturing new errors. */
2140 		ahci_pwrite(ap, AHCI_PREG_SERR, serr);
2141 
2142 		/* Acknowledge the interrupts we can recover from. */
2143 		ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_TFES |
2144 		    AHCI_PREG_IS_IFS);
2145 		is = ahci_pread(ap, AHCI_PREG_IS);
2146 
2147 		/* If device hasn't cleared its busy status, try to idle it. */
2148 		if (ISSET(tfd, AHCI_PREG_TFD_STS_BSY | AHCI_PREG_TFD_STS_DRQ)) {
2149 
2150 			if ((ap->ap_state == AP_S_PMP_PORT_PROBE) ||
2151 			    (ap->ap_state == AP_S_ERROR_RECOVERY)) {
2152 				/* can't reset the port here, just make sure
2153 				 * the operation fails and the port still works.
2154 				 */
2155 			} else if (ap->ap_pmp_ports != 0 && err_slot != -1) {
2156 				printf("%s: error on PMP port %d, idling "
2157 				    "device\n", PORTNAME(ap),
2158 				    ccb->ccb_xa.pmp_port);
2159 				if (ahci_pmp_port_softreset(ap,
2160 				        ccb->ccb_xa.pmp_port) == 0) {
2161 					printf("%s: unable to softreset port "
2162 					    "%d\n", PORTNAME(ap),
2163 					    ccb->ccb_xa.pmp_port);
2164 					if (ahci_pmp_port_portreset(ap,
2165 						ccb->ccb_xa.pmp_port)) {
2166 						printf("%s: failed to port "
2167 						    " reset %d, giving up on "
2168 						    "it\n", PORTNAME(ap),
2169 						    ccb->ccb_xa.pmp_port);
2170 						goto fatal;
2171 					}
2172 				}
2173 			} else {
2174 				printf("%s: attempting to idle device\n",
2175 				    PORTNAME(ap));
2176 				if (ahci_port_softreset(ap)) {
2177 					printf("%s: failed to soft reset "
2178 					    "device\n", PORTNAME(ap));
2179 					if (ahci_port_portreset(ap, 0)) {
2180 						printf("%s: failed to port "
2181 						    "reset device, give up on "
2182 						    "it\n", PORTNAME(ap));
2183 						goto fatal;
2184 					}
2185 				}
2186 			}
2187 
2188 			/* Had to reset device, can't gather extended info. */
2189 		} else if (ap->ap_sactive) {
2190 			/* Recover the NCQ error from log page 10h.
2191 			 * We can only have queued commands active for one port
2192 			 * at a time, so we know which device errored.
2193 			 */
2194 			ahci_port_read_ncq_error(ap, &err_slot,
2195 			    ap->ap_pmp_ncq_port);
2196 			if (err_slot < 0)
2197 				goto failall;
2198 
2199 			DPRINTF(AHCI_D_VERBOSE, "%s: NCQ errored slot %d\n",
2200 				PORTNAME(ap), err_slot);
2201 
2202 			ccb = &ap->ap_ccbs[err_slot];
2203 			if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2204 				printf("%s: NCQ errored slot %d is idle"
2205 				    " (%08x active)\n", PORTNAME(ap), err_slot,
2206 				    ci_saved);
2207 				goto failall;
2208 			}
2209 		} else {
2210 			/* Didn't reset, could gather extended info from log. */
2211 		}
2212 
2213 		/*
2214 		 * If we couldn't determine the errored slot, reset the port
2215 		 * and fail all the active slots.
2216 		 */
2217 		if (err_slot == -1) {
2218 			if (ahci_port_softreset(ap) != 0 &&
2219 			    ahci_port_portreset(ap, 0) != 0) {
2220 				printf("%s: couldn't reset after NCQ error, "
2221 				    "disabling device.\n", PORTNAME(ap));
2222 				goto fatal;
2223 			}
2224 			printf("%s: couldn't recover NCQ error, failing "
2225 			    "all outstanding commands.\n", PORTNAME(ap));
2226 			goto failall;
2227 		}
2228 
2229 		/* Clear the failed command in saved CI so completion runs. */
2230 		ci_saved &= ~(1 << err_slot);
2231 
2232 		/* Note the error in the ata_xfer. */
2233 		KASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
2234 		ccb->ccb_xa.state = ATA_S_ERROR;
2235 
2236 #ifdef DIAGNOSTIC
2237 		/* There may only be one outstanding standard command now. */
2238 		if (ap->ap_sactive == 0) {
2239 			tmp = ci_saved;
2240 			if (tmp) {
2241 				slot = ffs(tmp) - 1;
2242 				tmp &= ~(1 << slot);
2243 				KASSERT(tmp == 0);
2244 			}
2245 		}
2246 #endif
2247 	}
2248 
2249 	/* ATI SBx00 AHCI controllers respond to PMP probes with IPMS interrupts
2250 	 * when there's a normal SATA device attached.
2251 	 */
2252 	if ((ap->ap_state == AP_S_PMP_PROBE) &&
2253 	    (ap->ap_sc->sc_flags & AHCI_F_IPMS_PROBE) &&
2254 	    (is & AHCI_PREG_IS_IPMS)) {
2255 		slot = AHCI_PREG_CMD_CCS(ahci_pread(ap, AHCI_PREG_CMD));
2256 		DPRINTF(AHCI_D_INTR, "%s: slot %d received IPMS\n",
2257 		    PORTNAME(ap), slot);
2258 
2259 		ccb = &ap->ap_ccbs[slot];
2260 		ccb->ccb_xa.state = ATA_S_ERROR;
2261 
2262 		ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IPMS);
2263 		is &= ~AHCI_PREG_IS_IPMS;
2264 	}
2265 
2266 	/* ignore IFS errors while resetting a PMP port */
2267 	if ((is & AHCI_PREG_IS_IFS) /*&& ap->ap_pmp_ignore_ifs*/) {
2268 		DPRINTF(AHCI_D_INTR, "%s: ignoring IFS while resetting PMP "
2269 		    "port\n", PORTNAME(ap));
2270 
2271 		need_restart = 1;
2272 		ahci_pwrite(ap, AHCI_PREG_SERR, -1);
2273 		ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_IFS);
2274 		is &= ~AHCI_PREG_IS_IFS;
2275 		goto failall;
2276 	}
2277 
2278 	/* Check for remaining errors - they are fatal. */
2279 	if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS | AHCI_PREG_IS_IFS |
2280 	    AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
2281 		printf("%s: unrecoverable errors (IS: %b), disabling port.\n",
2282 		    PORTNAME(ap), is, AHCI_PFMT_IS);
2283 
2284 		/* XXX try recovery first */
2285 		goto fatal;
2286 	}
2287 
2288 	/* Fail all outstanding commands if we know the port won't recover. */
2289 	if (ap->ap_state == AP_S_FATAL_ERROR) {
2290 fatal:
2291 		ap->ap_state = AP_S_FATAL_ERROR;
2292 failall:
2293 
2294 		/* Ensure port is shut down. */
2295 		ahci_port_stop(ap, 1);
2296 
2297 		/* Error all the active slots. */
2298 		ci_masked = ci_saved & *active;
2299 		while (ci_masked) {
2300 			slot = ffs(ci_masked) - 1;
2301 			ccb = &ap->ap_ccbs[slot];
2302 			ci_masked &= ~(1 << slot);
2303 			ccb->ccb_xa.state = ATA_S_ERROR;
2304 		}
2305 
2306 		/* Run completion for all active slots. */
2307 		ci_saved &= ~*active;
2308 
2309 		/* Don't restart the port if our problems were deemed fatal. */
2310 		if (ap->ap_state == AP_S_FATAL_ERROR)
2311 			need_restart = 0;
2312 	}
2313 
2314 	/*
2315 	 * CCB completion is detected by noticing its slot's bit in CI has
2316 	 * changed to zero some time after we activated it.
2317 	 * If we are polling, we may only be interested in particular slot(s).
2318 	 */
2319 	ci_masked = ~ci_saved & *active & ci_mask;
2320 	while (ci_masked) {
2321 		slot = ffs(ci_masked) - 1;
2322 		ccb = &ap->ap_ccbs[slot];
2323 		ci_masked &= ~(1 << slot);
2324 
2325 		DPRINTF(AHCI_D_INTR, "%s: slot %d is complete%s\n",
2326 		    PORTNAME(ap), slot, ccb->ccb_xa.state == ATA_S_ERROR ?
2327 		    " (error)" : "");
2328 
2329 		bus_dmamap_sync(sc->sc_dmat,
2330 		    AHCI_DMA_MAP(ap->ap_dmamem_cmd_list),
2331 		    ccb->ccb_slot * sizeof(struct ahci_cmd_hdr),
2332 		    sizeof(struct ahci_cmd_hdr), BUS_DMASYNC_POSTWRITE);
2333 
2334 		bus_dmamap_sync(sc->sc_dmat,
2335 		    AHCI_DMA_MAP(ap->ap_dmamem_cmd_table),
2336 		    ccb->ccb_slot * sizeof(struct ahci_cmd_table),
2337 		    sizeof(struct ahci_cmd_table), BUS_DMASYNC_POSTWRITE);
2338 
2339 		bus_dmamap_sync(sc->sc_dmat,
2340 		    AHCI_DMA_MAP(ap->ap_dmamem_rfis), 0,
2341 		    sizeof(struct ahci_rfis), BUS_DMASYNC_POSTREAD);
2342 
2343 		*active &= ~(1 << ccb->ccb_slot);
2344 		/* Copy the rfis into the ccb if we were asked for it */
2345 		if (ccb->ccb_xa.state == ATA_S_ONCHIP &&
2346 		    ccb->ccb_xa.flags & ATA_F_GET_RFIS) {
2347 			memcpy(&ccb->ccb_xa.rfis,
2348 			       ap->ap_rfis->rfis,
2349 			       sizeof(struct ata_fis_d2h));
2350 		}
2351 
2352 		ccb->ccb_done(ccb);
2353 
2354 		processed |= 1 << ccb->ccb_slot;
2355 	}
2356 
2357 	if (need_restart) {
2358 		/* Restart command DMA on the port */
2359 		ahci_port_start(ap, 0);
2360 
2361 		/* Re-enable outstanding commands on port. */
2362 		if (ci_saved) {
2363 #ifdef DIAGNOSTIC
2364 			tmp = ci_saved;
2365 			while (tmp) {
2366 				slot = ffs(tmp) - 1;
2367 				tmp &= ~(1 << slot);
2368 				ccb = &ap->ap_ccbs[slot];
2369 				KASSERT(ccb->ccb_xa.state == ATA_S_ONCHIP);
2370 				KASSERT((!!(ccb->ccb_xa.flags & ATA_F_NCQ)) ==
2371 				    (!!ap->ap_sactive));
2372 			}
2373 #endif
2374 			DPRINTF(AHCI_D_VERBOSE, "%s: ahci_port_intr "
2375 			    "re-enabling%s slots %08x\n", PORTNAME(ap),
2376 			    ap->ap_sactive ? " NCQ" : "", ci_saved);
2377 
2378 			if (ap->ap_sactive)
2379 				ahci_pwrite(ap, AHCI_PREG_SACT, ci_saved);
2380 			ahci_pwrite(ap, AHCI_PREG_CI, ci_saved);
2381 		}
2382 	}
2383 
2384 	return (processed);
2385 }
2386 
2387 struct ahci_ccb *
2388 ahci_get_ccb(struct ahci_port *ap)
2389 {
2390 	struct ahci_ccb			*ccb;
2391 
2392 	mtx_enter(&ap->ap_ccb_mtx);
2393 	ccb = TAILQ_FIRST(&ap->ap_ccb_free);
2394 	if (ccb != NULL) {
2395 		KASSERT(ccb->ccb_xa.state == ATA_S_PUT);
2396 		TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
2397 		ccb->ccb_xa.state = ATA_S_SETUP;
2398 	}
2399 	mtx_leave(&ap->ap_ccb_mtx);
2400 
2401 	return (ccb);
2402 }
2403 
2404 void
2405 ahci_put_ccb(struct ahci_ccb *ccb)
2406 {
2407 	struct ahci_port		*ap = ccb->ccb_port;
2408 
2409 #ifdef DIAGNOSTIC
2410 	if (ccb->ccb_xa.state != ATA_S_COMPLETE &&
2411 	    ccb->ccb_xa.state != ATA_S_TIMEOUT &&
2412 	    ccb->ccb_xa.state != ATA_S_ERROR) {
2413 		printf("%s: invalid ata_xfer state %02x in ahci_put_ccb, "
2414 		    "slot %d\n", PORTNAME(ccb->ccb_port), ccb->ccb_xa.state,
2415 		    ccb->ccb_slot);
2416 	}
2417 #endif
2418 
2419 	ccb->ccb_xa.state = ATA_S_PUT;
2420 	mtx_enter(&ap->ap_ccb_mtx);
2421 	TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
2422 	mtx_leave(&ap->ap_ccb_mtx);
2423 }
2424 
2425 struct ahci_ccb *
2426 ahci_get_err_ccb(struct ahci_port *ap)
2427 {
2428 	struct ahci_ccb *err_ccb;
2429 	u_int32_t sact;
2430 
2431 	splassert(IPL_BIO);
2432 
2433 	/* No commands may be active on the chip. */
2434 	sact = ahci_pread(ap, AHCI_PREG_SACT);
2435 	if (sact != 0)
2436 		printf("ahci_get_err_ccb but SACT %08x != 0?\n", sact);
2437 	KASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
2438 
2439 #ifdef DIAGNOSTIC
2440 	KASSERT(ap->ap_err_busy == 0);
2441 	ap->ap_err_busy = 1;
2442 #endif
2443 	/* Save outstanding command state. */
2444 	ap->ap_err_saved_active = ap->ap_active;
2445 	ap->ap_err_saved_active_cnt = ap->ap_active_cnt;
2446 	ap->ap_err_saved_sactive = ap->ap_sactive;
2447 
2448 	/*
2449 	 * Pretend we have no commands outstanding, so that completions won't
2450 	 * run prematurely.
2451 	 */
2452 	ap->ap_active = ap->ap_active_cnt = ap->ap_sactive = 0;
2453 
2454 	/*
2455 	 * Grab a CCB to use for error recovery.  This should never fail, as
2456 	 * we ask atascsi to reserve one for us at init time.
2457 	 */
2458 	err_ccb = ap->ap_ccb_err;
2459 	err_ccb->ccb_xa.flags = 0;
2460 	err_ccb->ccb_xa.state = ATA_S_SETUP;
2461 	err_ccb->ccb_done = ahci_empty_done;
2462 
2463 	return (err_ccb);
2464 }
2465 
2466 void
2467 ahci_put_err_ccb(struct ahci_ccb *ccb)
2468 {
2469 	struct ahci_port *ap = ccb->ccb_port;
2470 	u_int32_t sact;
2471 
2472 	splassert(IPL_BIO);
2473 
2474 #ifdef DIAGNOSTIC
2475 	KASSERT(ap->ap_err_busy);
2476 #endif
2477 	/* No commands may be active on the chip */
2478 	sact = ahci_pread(ap, AHCI_PREG_SACT);
2479 	if (sact != 0)
2480 		printf("ahci_port_err_ccb_restore but SACT %08x != 0?\n", sact);
2481 	KASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
2482 
2483 #ifdef DIAGNOSTIC
2484 	/* Done with the CCB */
2485 	KASSERT(ccb == ap->ap_ccb_err);
2486 #endif
2487 
2488 	/* Restore outstanding command state */
2489 	ap->ap_sactive = ap->ap_err_saved_sactive;
2490 	ap->ap_active_cnt = ap->ap_err_saved_active_cnt;
2491 	ap->ap_active = ap->ap_err_saved_active;
2492 
2493 #ifdef DIAGNOSTIC
2494 	ap->ap_err_busy = 0;
2495 #endif
2496 }
2497 
2498 struct ahci_ccb *
2499 ahci_get_pmp_ccb(struct ahci_port *ap)
2500 {
2501 	struct ahci_ccb *ccb;
2502 	u_int32_t sact;
2503 
2504 	/* some PMP commands need to be issued on slot 1,
2505 	 * particularly the command that clears SRST and
2506 	 * fetches the device signature.
2507 	 *
2508 	 * ensure the chip is idle and ccb 1 is available.
2509 	 */
2510 	splassert(IPL_BIO);
2511 
2512 	sact = ahci_pread(ap, AHCI_PREG_SACT);
2513 	if (sact != 0)
2514 		printf("ahci_get_pmp_ccb; SACT %08x != 0\n", sact);
2515 	KASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
2516 
2517 	ccb = &ap->ap_ccbs[1];
2518 	KASSERT(ccb->ccb_xa.state == ATA_S_PUT);
2519 	ccb->ccb_xa.flags = 0;
2520 	ccb->ccb_done = ahci_pmp_cmd_done;
2521 
2522 	mtx_enter(&ap->ap_ccb_mtx);
2523 	TAILQ_REMOVE(&ap->ap_ccb_free, ccb, ccb_entry);
2524 	mtx_leave(&ap->ap_ccb_mtx);
2525 
2526 	return ccb;
2527 }
2528 
2529 void
2530 ahci_put_pmp_ccb(struct ahci_ccb *ccb)
2531 {
2532 	struct ahci_port *ap = ccb->ccb_port;
2533 	u_int32_t sact;
2534 
2535 	/* make sure this is the right ccb */
2536 	KASSERT(ccb == &ap->ap_ccbs[1]);
2537 
2538 	/* No commands may be active on the chip */
2539 	sact = ahci_pread(ap, AHCI_PREG_SACT);
2540 	if (sact != 0)
2541 		printf("ahci_port_err_ccb_restore but SACT %08x != 0?\n", sact);
2542 	KASSERT(ahci_pread(ap, AHCI_PREG_CI) == 0);
2543 
2544 	ccb->ccb_xa.state = ATA_S_PUT;
2545 	mtx_enter(&ap->ap_ccb_mtx);
2546 	TAILQ_INSERT_TAIL(&ap->ap_ccb_free, ccb, ccb_entry);
2547 	mtx_leave(&ap->ap_ccb_mtx);
2548 }
2549 
2550 int
2551 ahci_port_read_ncq_error(struct ahci_port *ap, int *err_slotp, int pmp_port)
2552 {
2553 	struct ahci_ccb			*ccb;
2554 	struct ahci_cmd_hdr		*cmd_slot;
2555 	u_int32_t			cmd;
2556 	struct ata_fis_h2d		*fis;
2557 	int				rc = EIO, oldstate;
2558 
2559 	DPRINTF(AHCI_D_VERBOSE, "%s: read log page\n", PORTNAME(ap));
2560 	oldstate = ap->ap_state;
2561 	ap->ap_state = AP_S_ERROR_RECOVERY;
2562 
2563 	/* Save command register state. */
2564 	cmd = ahci_pread(ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
2565 
2566 	/* Port should have been idled already.  Start it. */
2567 	KASSERT((cmd & AHCI_PREG_CMD_CR) == 0);
2568 	ahci_port_start(ap, 0);
2569 
2570 	/* Prep error CCB for READ LOG EXT, page 10h, 1 sector. */
2571 	ccb = ahci_get_err_ccb(ap);
2572 	ccb->ccb_xa.flags = ATA_F_NOWAIT | ATA_F_READ | ATA_F_POLL;
2573 	ccb->ccb_xa.data = ap->ap_err_scratch;
2574 	ccb->ccb_xa.datalen = 512;
2575 	cmd_slot = ccb->ccb_cmd_hdr;
2576 	memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
2577 
2578 	fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
2579 	fis->type = ATA_FIS_TYPE_H2D;
2580 	fis->flags = ATA_H2D_FLAGS_CMD | pmp_port;
2581 	fis->command = ATA_C_READ_LOG_EXT;
2582 	fis->lba_low = 0x10;		/* queued error log page (10h) */
2583 	fis->sector_count = 1;		/* number of sectors (1) */
2584 	fis->sector_count_exp = 0;
2585 	fis->lba_mid = 0;		/* starting offset */
2586 	fis->lba_mid_exp = 0;
2587 	fis->device = 0;
2588 
2589 	htolem16(&cmd_slot->flags, 5 /* FIS length: 5 DWORDS */ |
2590 	    (pmp_port << AHCI_CMD_LIST_FLAG_PMP_SHIFT));
2591 
2592 	if (ahci_load_prdt(ccb) != 0) {
2593 		rc = ENOMEM;	/* XXX caller must abort all commands */
2594 		goto err;
2595 	}
2596 
2597 	ccb->ccb_xa.state = ATA_S_PENDING;
2598 	if (ahci_poll(ccb, 1000, NULL) != 0 ||
2599 	    ccb->ccb_xa.state == ATA_S_ERROR)
2600 		goto err;
2601 
2602 	rc = 0;
2603 err:
2604 	/* Abort our command, if it failed, by stopping command DMA. */
2605 	if (rc != 0 && ISSET(ap->ap_active, 1 << ccb->ccb_slot)) {
2606 		printf("%s: log page read failed, slot %d was still active.\n",
2607 		    PORTNAME(ap), ccb->ccb_slot);
2608 		ahci_port_stop(ap, 0);
2609 	}
2610 
2611 	/* Done with the error CCB now. */
2612 	ahci_unload_prdt(ccb);
2613 	ahci_put_err_ccb(ccb);
2614 
2615 	/* Extract failed register set and tags from the scratch space. */
2616 	if (rc == 0) {
2617 		struct ata_log_page_10h		*log;
2618 		int				err_slot;
2619 
2620 		log = (struct ata_log_page_10h *)ap->ap_err_scratch;
2621 		if (ISSET(log->err_regs.type, ATA_LOG_10H_TYPE_NOTQUEUED)) {
2622 			/* Not queued bit was set - wasn't an NCQ error? */
2623 			printf("%s: read NCQ error page, but not an NCQ "
2624 			    "error?\n", PORTNAME(ap));
2625 			rc = ESRCH;
2626 		} else {
2627 			/* Copy back the log record as a D2H register FIS. */
2628 			*err_slotp = err_slot = log->err_regs.type &
2629 			    ATA_LOG_10H_TYPE_TAG_MASK;
2630 
2631 			ccb = &ap->ap_ccbs[err_slot];
2632 			memcpy(&ccb->ccb_xa.rfis, &log->err_regs,
2633 			    sizeof(struct ata_fis_d2h));
2634 			ccb->ccb_xa.rfis.type = ATA_FIS_TYPE_D2H;
2635 			ccb->ccb_xa.rfis.flags = 0;
2636 		}
2637 	}
2638 
2639 	/* Restore saved CMD register state */
2640 	ahci_pwrite(ap, AHCI_PREG_CMD, cmd);
2641 	ap->ap_state = oldstate;
2642 
2643 	return (rc);
2644 }
2645 
2646 struct ahci_dmamem *
2647 ahci_dmamem_alloc(struct ahci_softc *sc, size_t size)
2648 {
2649 	struct ahci_dmamem		*adm;
2650 	int				nsegs;
2651 
2652 	adm = malloc(sizeof(*adm), M_DEVBUF, M_NOWAIT | M_ZERO);
2653 	if (adm == NULL)
2654 		return (NULL);
2655 
2656 	adm->adm_size = size;
2657 
2658 	if (bus_dmamap_create(sc->sc_dmat, size, 1, size, 0,
2659 	    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &adm->adm_map) != 0)
2660 		goto admfree;
2661 
2662 	if (bus_dmamem_alloc(sc->sc_dmat, size, PAGE_SIZE, 0, &adm->adm_seg,
2663 	    1, &nsegs, BUS_DMA_NOWAIT | BUS_DMA_ZERO) != 0)
2664 		goto destroy;
2665 
2666 	if (bus_dmamem_map(sc->sc_dmat, &adm->adm_seg, nsegs, size,
2667 	    &adm->adm_kva, BUS_DMA_NOWAIT | BUS_DMA_COHERENT) != 0)
2668 		goto free;
2669 
2670 	if (bus_dmamap_load(sc->sc_dmat, adm->adm_map, adm->adm_kva, size,
2671 	    NULL, BUS_DMA_NOWAIT) != 0)
2672 		goto unmap;
2673 
2674 	return (adm);
2675 
2676 unmap:
2677 	bus_dmamem_unmap(sc->sc_dmat, adm->adm_kva, size);
2678 free:
2679 	bus_dmamem_free(sc->sc_dmat, &adm->adm_seg, 1);
2680 destroy:
2681 	bus_dmamap_destroy(sc->sc_dmat, adm->adm_map);
2682 admfree:
2683 	free(adm, M_DEVBUF, sizeof(*adm));
2684 
2685 	return (NULL);
2686 }
2687 
2688 void
2689 ahci_dmamem_free(struct ahci_softc *sc, struct ahci_dmamem *adm)
2690 {
2691 	bus_dmamap_unload(sc->sc_dmat, adm->adm_map);
2692 	bus_dmamem_unmap(sc->sc_dmat, adm->adm_kva, adm->adm_size);
2693 	bus_dmamem_free(sc->sc_dmat, &adm->adm_seg, 1);
2694 	bus_dmamap_destroy(sc->sc_dmat, adm->adm_map);
2695 	free(adm, M_DEVBUF, sizeof(*adm));
2696 }
2697 
2698 u_int32_t
2699 ahci_read(struct ahci_softc *sc, bus_size_t r)
2700 {
2701 	bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2702 	    BUS_SPACE_BARRIER_READ);
2703 	return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, r));
2704 }
2705 
2706 void
2707 ahci_write(struct ahci_softc *sc, bus_size_t r, u_int32_t v)
2708 {
2709 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, r, v);
2710 	bus_space_barrier(sc->sc_iot, sc->sc_ioh, r, 4,
2711 	    BUS_SPACE_BARRIER_WRITE);
2712 }
2713 
2714 int
2715 ahci_wait_ne(struct ahci_softc *sc, bus_size_t r, u_int32_t mask,
2716     u_int32_t target)
2717 {
2718 	int				i;
2719 
2720 	for (i = 0; i < 1000; i++) {
2721 		if ((ahci_read(sc, r) & mask) != target)
2722 			return (0);
2723 		delay(1000);
2724 	}
2725 
2726 	return (1);
2727 }
2728 
2729 u_int32_t
2730 ahci_pread(struct ahci_port *ap, bus_size_t r)
2731 {
2732 	bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2733 	    BUS_SPACE_BARRIER_READ);
2734 	return (bus_space_read_4(ap->ap_sc->sc_iot, ap->ap_ioh, r));
2735 }
2736 
2737 void
2738 ahci_pwrite(struct ahci_port *ap, bus_size_t r, u_int32_t v)
2739 {
2740 	bus_space_write_4(ap->ap_sc->sc_iot, ap->ap_ioh, r, v);
2741 	bus_space_barrier(ap->ap_sc->sc_iot, ap->ap_ioh, r, 4,
2742 	    BUS_SPACE_BARRIER_WRITE);
2743 }
2744 
2745 int
2746 ahci_pwait_eq(struct ahci_port *ap, bus_size_t r, u_int32_t mask,
2747     u_int32_t target, int n)
2748 {
2749 	int				i;
2750 
2751 	for (i = 0; i < n * 1000; i++) {
2752 		if ((ahci_pread(ap, r) & mask) == target)
2753 			return (0);
2754 		delay(1000);
2755 	}
2756 
2757 	return (1);
2758 }
2759 
2760 int
2761 ahci_ata_probe(void *xsc, int port, int lun)
2762 {
2763 	struct ahci_softc		*sc = xsc;
2764 	struct ahci_port		*ap = sc->sc_ports[port];
2765 
2766 	if (ap == NULL)
2767 		return (ATA_PORT_T_NONE);
2768 
2769 	if (lun != 0) {
2770 		int pmp_port = lun - 1;
2771 		if (pmp_port >= ap->ap_pmp_ports) {
2772 			return (ATA_PORT_T_NONE);
2773 		}
2774 		return (ahci_pmp_port_probe(ap, pmp_port));
2775 	} else {
2776 		return (ahci_port_signature(ap));
2777 	}
2778 }
2779 
2780 void
2781 ahci_ata_free(void *xsc, int port, int lun)
2782 {
2783 
2784 }
2785 
2786 struct ata_xfer *
2787 ahci_ata_get_xfer(void *aaa_cookie, int port)
2788 {
2789 	struct ahci_softc		*sc = aaa_cookie;
2790 	struct ahci_port		*ap = sc->sc_ports[port];
2791 	struct ahci_ccb			*ccb;
2792 
2793 	ccb = ahci_get_ccb(ap);
2794 	if (ccb == NULL) {
2795 		DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer: NULL ccb\n",
2796 		    PORTNAME(ap));
2797 		return (NULL);
2798 	}
2799 
2800 	DPRINTF(AHCI_D_XFER, "%s: ahci_ata_get_xfer got slot %d\n",
2801 	    PORTNAME(ap), ccb->ccb_slot);
2802 
2803 	return ((struct ata_xfer *)ccb);
2804 }
2805 
2806 void
2807 ahci_ata_put_xfer(struct ata_xfer *xa)
2808 {
2809 	struct ahci_ccb			*ccb = (struct ahci_ccb *)xa;
2810 
2811 	DPRINTF(AHCI_D_XFER, "ahci_ata_put_xfer slot %d\n", ccb->ccb_slot);
2812 
2813 	ahci_put_ccb(ccb);
2814 }
2815 
2816 void
2817 ahci_ata_cmd(struct ata_xfer *xa)
2818 {
2819 	struct ahci_ccb			*ccb = (struct ahci_ccb *)xa;
2820 	struct ahci_cmd_hdr		*cmd_slot;
2821 	int				s;
2822 	u_int16_t			flags;
2823 
2824 	if (ccb->ccb_port->ap_state == AP_S_FATAL_ERROR)
2825 		goto failcmd;
2826 
2827 	ccb->ccb_done = ahci_ata_cmd_done;
2828 
2829 	cmd_slot = ccb->ccb_cmd_hdr;
2830 	flags = 5 /* FIS length (in DWORDs) */;
2831 	flags |= xa->pmp_port << AHCI_CMD_LIST_FLAG_PMP_SHIFT;
2832 
2833 	if (xa->flags & ATA_F_WRITE)
2834 		flags |= AHCI_CMD_LIST_FLAG_W;
2835 
2836 	if (xa->flags & ATA_F_PACKET)
2837 		flags |= AHCI_CMD_LIST_FLAG_A;
2838 
2839 	htolem16(&cmd_slot->flags, flags);
2840 
2841 	if (ahci_load_prdt(ccb) != 0)
2842 		goto failcmd;
2843 
2844 	timeout_set(&xa->stimeout, ahci_ata_cmd_timeout, ccb);
2845 
2846 	xa->state = ATA_S_PENDING;
2847 
2848 	if (xa->flags & ATA_F_POLL)
2849 		ahci_poll(ccb, xa->timeout, ahci_ata_cmd_timeout);
2850 	else {
2851 		s = splbio();
2852 		timeout_add_msec(&xa->stimeout, xa->timeout);
2853 		ahci_start(ccb);
2854 		splx(s);
2855 	}
2856 
2857 	return;
2858 
2859 failcmd:
2860 	s = splbio();
2861 	xa->state = ATA_S_ERROR;
2862 	ata_complete(xa);
2863 	splx(s);
2864 }
2865 
2866 void
2867 ahci_pmp_cmd_done(struct ahci_ccb *ccb)
2868 {
2869 	struct ata_xfer			*xa = &ccb->ccb_xa;
2870 
2871 	if (xa->state == ATA_S_ONCHIP || xa->state == ATA_S_ERROR)
2872 		ahci_issue_pending_commands(ccb->ccb_port,
2873 		    xa->flags & ATA_F_NCQ);
2874 
2875 	xa->state = ATA_S_COMPLETE;
2876 }
2877 
2878 
2879 void
2880 ahci_ata_cmd_done(struct ahci_ccb *ccb)
2881 {
2882 	struct ata_xfer			*xa = &ccb->ccb_xa;
2883 
2884 	timeout_del(&xa->stimeout);
2885 
2886 	if (xa->state == ATA_S_ONCHIP || xa->state == ATA_S_ERROR)
2887 		ahci_issue_pending_commands(ccb->ccb_port,
2888 		    xa->flags & ATA_F_NCQ);
2889 
2890 	ahci_unload_prdt(ccb);
2891 
2892 	if (xa->state == ATA_S_ONCHIP)
2893 		xa->state = ATA_S_COMPLETE;
2894 #ifdef DIAGNOSTIC
2895 	else if (xa->state != ATA_S_ERROR && xa->state != ATA_S_TIMEOUT)
2896 		printf("%s: invalid ata_xfer state %02x in ahci_ata_cmd_done, "
2897 		    "slot %d\n", PORTNAME(ccb->ccb_port), xa->state,
2898 		    ccb->ccb_slot);
2899 #endif
2900 	if (xa->state != ATA_S_TIMEOUT)
2901 		ata_complete(xa);
2902 }
2903 
2904 void
2905 ahci_ata_cmd_timeout(void *arg)
2906 {
2907 	struct ahci_ccb			*ccb = arg;
2908 	struct ata_xfer			*xa = &ccb->ccb_xa;
2909 	struct ahci_port		*ap = ccb->ccb_port;
2910 	int				s, ccb_was_started, ncq_cmd;
2911 	volatile u_int32_t		*active;
2912 
2913 	s = splbio();
2914 
2915 	ncq_cmd = (xa->flags & ATA_F_NCQ);
2916 	active = ncq_cmd ? &ap->ap_sactive : &ap->ap_active;
2917 
2918 	if (ccb->ccb_xa.state == ATA_S_PENDING) {
2919 		DPRINTF(AHCI_D_TIMEOUT, "%s: command for slot %d timed out "
2920 		    "before it got on chip\n", PORTNAME(ap), ccb->ccb_slot);
2921 		TAILQ_REMOVE(&ap->ap_ccb_pending, ccb, ccb_entry);
2922 		ccb_was_started = 0;
2923 	} else if (ccb->ccb_xa.state == ATA_S_ONCHIP && ahci_port_intr(ap,
2924 	    1 << ccb->ccb_slot)) {
2925 		DPRINTF(AHCI_D_TIMEOUT, "%s: final poll of port completed "
2926 		    "command in slot %d\n", PORTNAME(ap), ccb->ccb_slot);
2927 		goto ret;
2928 	} else if (ccb->ccb_xa.state != ATA_S_ONCHIP) {
2929 		DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d already "
2930 		    "handled%s\n", PORTNAME(ap), ccb->ccb_slot,
2931 		    ISSET(*active, 1 << ccb->ccb_slot) ?
2932 		    " but slot is still active?" : ".");
2933 		goto ret;
2934 	} else if (!ISSET(ahci_pread(ap, ncq_cmd ? AHCI_PREG_SACT :
2935 	    AHCI_PREG_CI), 1 << ccb->ccb_slot) && ISSET(*active,
2936 	    1 << ccb->ccb_slot)) {
2937 		DPRINTF(AHCI_D_TIMEOUT, "%s: command slot %d completed but "
2938 		    "IRQ handler didn't detect it.  Why?\n", PORTNAME(ap),
2939 		    ccb->ccb_slot);
2940 		*active &= ~(1 << ccb->ccb_slot);
2941 		ccb->ccb_done(ccb);
2942 		goto ret;
2943 	} else {
2944 		ccb_was_started = 1;
2945 	}
2946 
2947 	/* Complete the slot with a timeout error. */
2948 	ccb->ccb_xa.state = ATA_S_TIMEOUT;
2949 	*active &= ~(1 << ccb->ccb_slot);
2950 	DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (1)\n", PORTNAME(ap));
2951 	ccb->ccb_done(ccb);	/* This won't issue pending commands or run the
2952 				   atascsi completion. */
2953 
2954 	/* Reset port to abort running command. */
2955 	if (ccb_was_started) {
2956 		DPRINTF(AHCI_D_TIMEOUT, "%s: resetting port to abort%s command "
2957 		    "in slot %d, pmp port %d, active %08x\n", PORTNAME(ap),
2958 		    ncq_cmd ? " NCQ" : "", ccb->ccb_slot, xa->pmp_port, *active);
2959 		if (ahci_port_softreset(ap) != 0 && ahci_port_portreset(ap, 0)
2960 		    != 0) {
2961 			printf("%s: failed to reset port during timeout "
2962 			    "handling, disabling it\n", PORTNAME(ap));
2963 			ap->ap_state = AP_S_FATAL_ERROR;
2964 		}
2965 
2966 		/* Restart any other commands that were aborted by the reset. */
2967 		if (*active) {
2968 			DPRINTF(AHCI_D_TIMEOUT, "%s: re-enabling%s slots "
2969 			    "%08x\n", PORTNAME(ap), ncq_cmd ? " NCQ" : "",
2970 			    *active);
2971 			if (ncq_cmd)
2972 				ahci_pwrite(ap, AHCI_PREG_SACT, *active);
2973 			ahci_pwrite(ap, AHCI_PREG_CI, *active);
2974 		}
2975 	}
2976 
2977 	/* Issue any pending commands now. */
2978 	DPRINTF(AHCI_D_TIMEOUT, "%s: issue pending\n", PORTNAME(ap));
2979 	if (ccb_was_started)
2980 		ahci_issue_pending_commands(ap, ncq_cmd);
2981 	else if (ap->ap_active == 0)
2982 		ahci_issue_pending_ncq_commands(ap);
2983 
2984 	/* Complete the timed out ata_xfer I/O (may generate new I/O). */
2985 	DPRINTF(AHCI_D_TIMEOUT, "%s: run completion (2)\n", PORTNAME(ap));
2986 	ata_complete(xa);
2987 
2988 	DPRINTF(AHCI_D_TIMEOUT, "%s: splx\n", PORTNAME(ap));
2989 ret:
2990 	splx(s);
2991 }
2992 
2993 void
2994 ahci_empty_done(struct ahci_ccb *ccb)
2995 {
2996 	if (ccb->ccb_xa.state != ATA_S_ERROR)
2997 		ccb->ccb_xa.state = ATA_S_COMPLETE;
2998 }
2999 
3000 int
3001 ahci_pmp_read(struct ahci_port *ap, int target, int which, u_int32_t *datap)
3002 {
3003 	struct ahci_ccb	*ccb;
3004 	struct ata_fis_h2d *fis;
3005 	int error;
3006 
3007 	ccb = ahci_get_pmp_ccb(ap);
3008 	if (ccb == NULL) {
3009 		printf("%s: NULL ccb!\n", PORTNAME(ap));
3010 		return (1);
3011 	}
3012 	ccb->ccb_xa.flags = ATA_F_POLL | ATA_F_GET_RFIS;
3013 	ccb->ccb_xa.pmp_port = SATA_PMP_CONTROL_PORT;
3014 	ccb->ccb_xa.state = ATA_S_PENDING;
3015 
3016 	memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
3017 	fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
3018 	fis->type = ATA_FIS_TYPE_H2D;
3019 	fis->flags = ATA_H2D_FLAGS_CMD | SATA_PMP_CONTROL_PORT;
3020 	fis->command = ATA_C_READ_PM;
3021 	fis->features = which;
3022 	fis->device = target | ATA_H2D_DEVICE_LBA;
3023 	fis->control = ATA_FIS_CONTROL_4BIT;
3024 
3025 	if (ahci_poll(ccb, 1000, ahci_pmp_probe_timeout) != 0) {
3026 		error = 1;
3027 	} else {
3028 		*datap = ccb->ccb_xa.rfis.sector_count |
3029 		    (ccb->ccb_xa.rfis.lba_low << 8) |
3030 		    (ccb->ccb_xa.rfis.lba_mid << 16) |
3031 		    (ccb->ccb_xa.rfis.lba_high << 24);
3032 		error = 0;
3033 	}
3034 	ahci_put_pmp_ccb(ccb);
3035 	return (error);
3036 }
3037 
3038 int
3039 ahci_pmp_write(struct ahci_port *ap, int target, int which, u_int32_t data)
3040 {
3041 	struct ahci_ccb	*ccb;
3042 	struct ata_fis_h2d *fis;
3043 	int error;
3044 
3045 	ccb = ahci_get_pmp_ccb(ap);
3046 	if (ccb == NULL) {
3047 		printf("%s: NULL ccb!\n", PORTNAME(ap));
3048 		return (1);
3049 	}
3050 	ccb->ccb_xa.flags = ATA_F_POLL;
3051 	ccb->ccb_xa.pmp_port = SATA_PMP_CONTROL_PORT;
3052 	ccb->ccb_xa.state = ATA_S_PENDING;
3053 
3054 	memset(ccb->ccb_cmd_table, 0, sizeof(struct ahci_cmd_table));
3055 	fis = (struct ata_fis_h2d *)ccb->ccb_cmd_table->cfis;
3056 	fis->type = ATA_FIS_TYPE_H2D;
3057 	fis->flags = ATA_H2D_FLAGS_CMD | SATA_PMP_CONTROL_PORT;
3058 	fis->command = ATA_C_WRITE_PM;
3059 	fis->features = which;
3060 	fis->device = target | ATA_H2D_DEVICE_LBA;
3061 	fis->sector_count = (u_int8_t)data;
3062 	fis->lba_low = (u_int8_t)(data >> 8);
3063 	fis->lba_mid = (u_int8_t)(data >> 16);
3064 	fis->lba_high = (u_int8_t)(data >> 24);
3065 	fis->control = ATA_FIS_CONTROL_4BIT;
3066 
3067 	error = ahci_poll(ccb, 1000, ahci_pmp_probe_timeout);
3068 	ahci_put_pmp_ccb(ccb);
3069 	return (error);
3070 }
3071 
3072 int
3073 ahci_pmp_phy_status(struct ahci_port *ap, int target, u_int32_t *datap)
3074 {
3075 	int error;
3076 
3077 	error = ahci_pmp_read(ap, target, SATA_PMREG_SSTS, datap);
3078 	if (error == 0)
3079 		error = ahci_pmp_write(ap, target, SATA_PMREG_SERR, -1);
3080 	if (error)
3081 		*datap = 0;
3082 
3083 	return (error);
3084 }
3085 
3086 int
3087 ahci_pmp_identify(struct ahci_port *ap, int *ret_nports)
3088 {
3089 	u_int32_t chipid;
3090 	u_int32_t rev;
3091 	u_int32_t nports;
3092 	u_int32_t features;
3093 	u_int32_t enabled;
3094 	int s;
3095 
3096 	s = splbio();
3097 
3098 	if (ahci_pmp_read(ap, 15, 0, &chipid) ||
3099 	    ahci_pmp_read(ap, 15, 1, &rev) ||
3100 	    ahci_pmp_read(ap, 15, 2, &nports) ||
3101 	    ahci_pmp_read(ap, 15, SATA_PMREG_FEA, &features) ||
3102 	    ahci_pmp_read(ap, 15, SATA_PMREG_FEAEN, &enabled)) {
3103 		printf("%s: port multiplier identification failed\n",
3104 		    PORTNAME(ap));
3105 		splx(s);
3106 		return (1);
3107 	}
3108 	splx(s);
3109 
3110 	nports &= 0x0F;
3111 
3112 	/* ignore SEMB port on SiI3726 port multiplier chips */
3113 	if (chipid == 0x37261095) {
3114 		nports--;
3115 	}
3116 
3117 	printf("%s: port multiplier found: chip=%08x rev=0x%b nports=%d, "
3118 	    "features: 0x%b, enabled: 0x%b\n", PORTNAME(ap), chipid, rev,
3119 	    SATA_PFMT_PM_REV, nports, features, SATA_PFMT_PM_FEA, enabled,
3120 	    SATA_PFMT_PM_FEA);
3121 
3122 	*ret_nports = nports;
3123 	return (0);
3124 }
3125 
3126 
3127 #ifdef HIBERNATE
3128 void
3129 ahci_hibernate_io_start(struct ahci_port *ap, struct ahci_ccb *ccb)
3130 {
3131 	ccb->ccb_cmd_hdr->prdbc = 0;
3132 	ahci_pwrite(ap, AHCI_PREG_CI, 1 << ccb->ccb_slot);
3133 }
3134 
3135 int
3136 ahci_hibernate_io_poll(struct ahci_port *ap, struct ahci_ccb *ccb)
3137 {
3138 	u_int32_t			is, ci_saved;
3139 	int				process_error = 0;
3140 
3141 	is = ahci_pread(ap, AHCI_PREG_IS);
3142 
3143 	ci_saved = ahci_pread(ap, AHCI_PREG_CI);
3144 
3145 	if (is & AHCI_PREG_IS_DHRS) {
3146 		u_int32_t tfd;
3147 		u_int32_t cmd;
3148 
3149 		tfd = ahci_pread(ap, AHCI_PREG_TFD);
3150 		cmd = ahci_pread(ap, AHCI_PREG_CMD);
3151 		if ((tfd & AHCI_PREG_TFD_STS_ERR) &&
3152 		    (cmd & AHCI_PREG_CMD_CR) == 0) {
3153 			process_error = 1;
3154 		} else {
3155 			ahci_pwrite(ap, AHCI_PREG_IS, AHCI_PREG_IS_DHRS);
3156 		}
3157 	} else if (is & (AHCI_PREG_IS_TFES | AHCI_PREG_IS_HBFS |
3158 	    AHCI_PREG_IS_IFS | AHCI_PREG_IS_OFS | AHCI_PREG_IS_UFS)) {
3159 		process_error = 1;
3160 	}
3161 
3162 	/* Command failed.  See AHCI 1.1 spec 6.2.2.1 and 6.2.2.2. */
3163 	if (process_error) {
3164 
3165 		/* Turn off ST to clear CI and SACT. */
3166 		ahci_port_stop(ap, 0);
3167 
3168 		/* just return an error indicator?  we can't meaningfully
3169 		 * recover, and on the way back out we'll DVACT_RESUME which
3170 		 * resets and reinits the port.
3171 		 */
3172 		return (EIO);
3173 	}
3174 
3175 	/* command is finished when the bit in CI for the slot goes to 0 */
3176 	if (ci_saved & (1 << ccb->ccb_slot)) {
3177 		return (EAGAIN);
3178 	}
3179 
3180 	return (0);
3181 }
3182 
3183 void
3184 ahci_hibernate_load_prdt(struct ahci_ccb *ccb)
3185 {
3186 	struct ata_xfer			*xa = &ccb->ccb_xa;
3187 	struct ahci_prdt		*prdt = ccb->ccb_cmd_table->prdt;
3188 	struct ahci_cmd_hdr		*cmd_slot = ccb->ccb_cmd_hdr;
3189 	int				i;
3190 	paddr_t				data_phys;
3191 	u_int64_t			data_bus_phys;
3192 	vaddr_t				data_addr;
3193 	size_t				seglen;
3194 	size_t				buflen;
3195 
3196 	if (xa->datalen == 0) {
3197 		ccb->ccb_cmd_hdr->prdtl = 0;
3198 		return;
3199 	}
3200 
3201 	/* derived from i386/amd64 _bus_dma_load_buffer;
3202 	 * for amd64 the buffer will always be dma safe.
3203 	 */
3204 
3205 	buflen = xa->datalen;
3206 	data_addr = (vaddr_t)xa->data;
3207 	for (i = 0; buflen > 0; i++) {
3208 		pmap_extract(pmap_kernel(), data_addr, &data_phys);
3209 		data_bus_phys = data_phys;
3210 
3211 		seglen = PAGE_SIZE - ((u_long)data_addr & PGOFSET);
3212 		if (buflen < seglen)
3213 			seglen = buflen;
3214 
3215 		ahci_load_prdt_seg(&prdt[i], data_bus_phys, seglen, 0);
3216 
3217 		data_addr += seglen;
3218 		buflen -= seglen;
3219 	}
3220 
3221 	htolem16(&cmd_slot->prdtl, i);
3222 }
3223 
3224 int
3225 ahci_hibernate_io(dev_t dev, daddr_t blkno, vaddr_t addr, size_t size,
3226     int op, void *page)
3227 {
3228 	/* we use the 'real' ahci_port and ahci_softc here, but
3229 	 * never write to them
3230 	 */
3231 	struct {
3232 		struct ahci_cmd_hdr cmd_hdr[32]; /* page aligned, 1024 bytes */
3233 		struct ahci_rfis rfis;		 /* 1k aligned, 256 bytes */
3234 		/* cmd table isn't actually used because of mysteries */
3235 		struct ahci_cmd_table cmd_table; /* 256 aligned, 512 bytes */
3236 		struct ahci_port *ap;
3237 		struct ahci_ccb ccb_buf;
3238 		struct ahci_ccb *ccb;
3239 		struct ahci_cmd_hdr *hdr_buf;
3240 		int pmp_port;
3241 		daddr_t poffset;
3242 		size_t psize;
3243 	} *my = page;
3244 	struct ata_fis_h2d *fis;
3245 	u_int32_t sector_count;
3246 	struct ahci_cmd_hdr *cmd_slot;
3247 	int rc;
3248 	int timeout;
3249 	u_int16_t flags;
3250 
3251 	if (op == HIB_INIT) {
3252 		struct device *disk;
3253 		struct device *scsibus;
3254 		struct ahci_softc *sc;
3255 		extern struct cfdriver sd_cd;
3256 		struct scsi_link *link;
3257 		struct scsibus_softc *bus_sc;
3258 		int port;
3259 		paddr_t page_phys;
3260 		u_int64_t item_phys;
3261 		u_int32_t cmd;
3262 
3263 		my->poffset = blkno;
3264 		my->psize = size;
3265 
3266 		/* map dev to an ahci port */
3267 		disk = disk_lookup(&sd_cd, DISKUNIT(dev));
3268 		scsibus = disk->dv_parent;
3269 		sc = (struct ahci_softc *)disk->dv_parent->dv_parent;
3270 
3271 		/* find the scsi_link for the device, which has the port */
3272 		port = -1;
3273 		bus_sc = (struct scsibus_softc *)scsibus;
3274 		SLIST_FOREACH(link, &bus_sc->sc_link_list, bus_list) {
3275 			if (link->device_softc == disk) {
3276 				/* link->adapter_softc == sc->sc_atascsi */
3277 				port = link->target;
3278 				if (link->lun > 0)
3279 					my->pmp_port = link->lun - 1;
3280 				else
3281 					my->pmp_port = 0;
3282 
3283 				break;
3284 			}
3285 		}
3286 		if (port == -1) {
3287 			/* don't know where the disk is */
3288 			return (EIO);
3289 		}
3290 
3291 		my->ap = sc->sc_ports[port];
3292 
3293 		/* we're going to use the first command slot,
3294 		 * so ensure it's not already in use
3295 		 */
3296 		if (my->ap->ap_ccbs[0].ccb_xa.state != ATA_S_PUT) {
3297 			/* this shouldn't happen, we should be idle */
3298 			return (EIO);
3299 		}
3300 
3301 		/* stop the port so we can relocate to the hibernate page */
3302 		if (ahci_port_stop(my->ap, 1)) {
3303 			return (EIO);
3304 		}
3305 		ahci_pwrite(my->ap, AHCI_PREG_SCTL, 0);
3306 
3307 		pmap_extract(pmap_kernel(), (vaddr_t)page, &page_phys);
3308 
3309 		/* Setup RFIS base address */
3310 		item_phys = page_phys + ((void *)&my->rfis - page);
3311 		ahci_pwrite(my->ap, AHCI_PREG_FBU,
3312 		    (u_int32_t)(item_phys >> 32));
3313 		ahci_pwrite(my->ap, AHCI_PREG_FB, (u_int32_t)item_phys);
3314 
3315 		/* Enable FIS reception and activate port. */
3316 		cmd = ahci_pread(my->ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
3317 		cmd |= AHCI_PREG_CMD_FRE | AHCI_PREG_CMD_POD |
3318 		    AHCI_PREG_CMD_SUD;
3319 		ahci_pwrite(my->ap, AHCI_PREG_CMD, cmd |
3320 		    AHCI_PREG_CMD_ICC_ACTIVE);
3321 
3322 		/* Check whether port activated.  */
3323 		cmd = ahci_pread(my->ap, AHCI_PREG_CMD) & ~AHCI_PREG_CMD_ICC;
3324 		if (!ISSET(cmd, AHCI_PREG_CMD_FRE)) {
3325 			return (EIO);
3326 		}
3327 
3328 		/* Set up the single CCB */
3329 		my->ccb = &my->ccb_buf;
3330 		my->ccb->ccb_slot = 0;
3331 		my->ccb->ccb_port = my->ap;
3332 
3333 		/* Setup command list base address */
3334 		item_phys = page_phys + ((void *)&my->cmd_hdr - page);
3335 		ahci_pwrite(my->ap, AHCI_PREG_CLBU,
3336 		    (u_int32_t)(item_phys >> 32));
3337 		ahci_pwrite(my->ap, AHCI_PREG_CLB, (u_int32_t)item_phys);
3338 
3339 		my->ccb->ccb_cmd_hdr = &my->cmd_hdr[0];
3340 
3341 		/* use existing cmd table - don't know why moving to a new one fails */
3342 		my->ccb->ccb_cmd_table = my->ap->ap_ccbs[0].ccb_cmd_table;
3343 		pmap_extract(pmap_kernel(),
3344 		    (vaddr_t)AHCI_DMA_KVA(my->ap->ap_dmamem_cmd_table),
3345 		    &page_phys);
3346 		item_phys = page_phys;
3347 #if 0
3348 		/* use cmd table in hibernate page (doesn't work) */
3349 		my->ccb->ccb_cmd_table = &my->cmd_table;
3350 		item_phys = page_phys + ((void *)&my->cmd_table - page);
3351 #endif
3352 		htolem64(&my->ccb->ccb_cmd_hdr->ctba, item_phys);
3353 
3354 		my->ccb->ccb_xa.fis =
3355 		    (struct ata_fis_h2d *)my->ccb->ccb_cmd_table->cfis;
3356 		my->ccb->ccb_xa.packetcmd = my->ccb->ccb_cmd_table->acmd;
3357 		my->ccb->ccb_xa.tag = 0;
3358 
3359 		/* Wait for ICC change to complete */
3360 		ahci_pwait_clr(my->ap, AHCI_PREG_CMD, AHCI_PREG_CMD_ICC, 1);
3361 
3362 		if (ahci_port_start(my->ap, 0)) {
3363 			return (EIO);
3364 		}
3365 
3366 		/* Flush interrupts for port */
3367 		ahci_pwrite(my->ap, AHCI_PREG_IS, ahci_pread(my->ap,
3368 		    AHCI_PREG_IS));
3369 		ahci_write(sc, AHCI_REG_IS, 1 << port);
3370 
3371 		ahci_enable_interrupts(my->ap);
3372 		return (0);
3373 	} else if (op == HIB_DONE) {
3374 		ahci_activate(&my->ap->ap_sc->sc_dev, DVACT_RESUME);
3375 		return (0);
3376 	}
3377 
3378 	if (blkno > my->psize)
3379 		return (E2BIG);
3380 	blkno += my->poffset;
3381 
3382 	/* build fis */
3383 	sector_count = size / 512;	/* dlg promises this is okay */
3384 	my->ccb->ccb_xa.flags = op == HIB_W ? ATA_F_WRITE : ATA_F_READ;
3385 	fis = my->ccb->ccb_xa.fis;
3386 	fis->flags = ATA_H2D_FLAGS_CMD | my->pmp_port;
3387 	fis->lba_low = blkno & 0xff;
3388 	fis->lba_mid = (blkno >> 8) & 0xff;
3389 	fis->lba_high = (blkno >> 16) & 0xff;
3390 
3391 	if (sector_count > 0x100 || blkno > 0xfffffff) {
3392 		/* Use LBA48 */
3393 		fis->command = op == HIB_W ? ATA_C_WRITEDMA_EXT :
3394 		    ATA_C_READDMA_EXT;
3395 		fis->device = ATA_H2D_DEVICE_LBA;
3396 		fis->lba_low_exp = (blkno >> 24) & 0xff;
3397 		fis->lba_mid_exp = (blkno >> 32) & 0xff;
3398 		fis->lba_high_exp = (blkno >> 40) & 0xff;
3399 		fis->sector_count = sector_count & 0xff;
3400 		fis->sector_count_exp = (sector_count >> 8) & 0xff;
3401 	} else {
3402 		/* Use LBA */
3403 		fis->command = op == HIB_W ? ATA_C_WRITEDMA : ATA_C_READDMA;
3404 		fis->device = ATA_H2D_DEVICE_LBA | ((blkno >> 24) & 0x0f);
3405 		fis->sector_count = sector_count & 0xff;
3406 	}
3407 
3408 	my->ccb->ccb_xa.data = (void *)addr;
3409 	my->ccb->ccb_xa.datalen = size;
3410 	my->ccb->ccb_xa.pmp_port = my->pmp_port;
3411 	my->ccb->ccb_xa.flags |= ATA_F_POLL;
3412 
3413 	cmd_slot = my->ccb->ccb_cmd_hdr;
3414 	flags = 5; /* FIS length (in DWORDs) */
3415 	flags |= my->pmp_port << AHCI_CMD_LIST_FLAG_PMP_SHIFT;
3416 
3417 	if (op == HIB_W)
3418 		flags |= AHCI_CMD_LIST_FLAG_W;
3419 
3420 	htolem16(&cmd_slot->flags, flags);
3421 
3422 	ahci_hibernate_load_prdt(my->ccb);
3423 
3424 	ahci_hibernate_io_start(my->ap, my->ccb);
3425 	timeout = 1000000;
3426 	while ((rc = ahci_hibernate_io_poll(my->ap, my->ccb)) == EAGAIN) {
3427 		delay(1);
3428 		timeout--;
3429 		if (timeout == 0) {
3430 			return (EIO);
3431 		}
3432 	}
3433 
3434 	return (0);
3435 }
3436 
3437 #endif
3438