xref: /freebsd/sys/dev/ahci/ahci.c (revision 06c3fb27)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009-2012 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/module.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/bus.h>
34 #include <sys/conf.h>
35 #include <sys/endian.h>
36 #include <sys/malloc.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/sbuf.h>
40 #include <sys/sysctl.h>
41 #include <machine/stdarg.h>
42 #include <machine/resource.h>
43 #include <machine/bus.h>
44 #include <sys/rman.h>
45 #include "ahci.h"
46 
47 #include <cam/cam.h>
48 #include <cam/cam_ccb.h>
49 #include <cam/cam_sim.h>
50 #include <cam/cam_xpt_sim.h>
51 #include <cam/cam_debug.h>
52 
53 /* local prototypes */
54 static void ahci_intr(void *data);
55 static void ahci_intr_one(void *data);
56 static void ahci_intr_one_edge(void *data);
57 static int ahci_ch_init(device_t dev);
58 static int ahci_ch_deinit(device_t dev);
59 static int ahci_ch_suspend(device_t dev);
60 static int ahci_ch_resume(device_t dev);
61 static void ahci_ch_pm(void *arg);
62 static void ahci_ch_intr(void *arg);
63 static void ahci_ch_intr_direct(void *arg);
64 static void ahci_ch_intr_main(struct ahci_channel *ch, uint32_t istatus);
65 static void ahci_begin_transaction(struct ahci_channel *ch, union ccb *ccb);
66 static void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
67 static void ahci_execute_transaction(struct ahci_slot *slot);
68 static void ahci_timeout(void *arg);
69 static void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
70 static int ahci_setup_fis(struct ahci_channel *ch, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
71 static void ahci_dmainit(device_t dev);
72 static void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
73 static void ahci_dmafini(device_t dev);
74 static void ahci_slotsalloc(device_t dev);
75 static void ahci_slotsfree(device_t dev);
76 static void ahci_reset(struct ahci_channel *ch);
77 static void ahci_start(struct ahci_channel *ch, int fbs);
78 static void ahci_stop(struct ahci_channel *ch);
79 static void ahci_clo(struct ahci_channel *ch);
80 static void ahci_start_fr(struct ahci_channel *ch);
81 static void ahci_stop_fr(struct ahci_channel *ch);
82 static int ahci_phy_check_events(struct ahci_channel *ch, u_int32_t serr);
83 static uint32_t ahci_ch_detval(struct ahci_channel *ch, uint32_t val);
84 
85 static int ahci_sata_connect(struct ahci_channel *ch);
86 static int ahci_sata_phy_reset(struct ahci_channel *ch);
87 static int ahci_wait_ready(struct ahci_channel *ch, int t, int t0);
88 
89 static void ahci_issue_recovery(struct ahci_channel *ch);
90 static void ahci_process_read_log(struct ahci_channel *ch, union ccb *ccb);
91 static void ahci_process_request_sense(struct ahci_channel *ch, union ccb *ccb);
92 
93 static void ahciaction(struct cam_sim *sim, union ccb *ccb);
94 static void ahcipoll(struct cam_sim *sim);
95 
96 static MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
97 
98 #define recovery_type		spriv_field0
99 #define RECOVERY_NONE		0
100 #define RECOVERY_READ_LOG	1
101 #define RECOVERY_REQUEST_SENSE	2
102 #define recovery_slot		spriv_field1
103 
104 static uint32_t
105 ahci_ch_detval(struct ahci_channel *ch, uint32_t val)
106 {
107 
108 	return ch->disablephy ? ATA_SC_DET_DISABLE : val;
109 }
110 
111 int
112 ahci_ctlr_setup(device_t dev)
113 {
114 	struct ahci_controller *ctlr = device_get_softc(dev);
115 	/* Clear interrupts */
116 	ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
117 	/* Configure CCC */
118 	if (ctlr->ccc) {
119 		ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
120 		ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
121 		    (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
122 		    (4 << AHCI_CCCC_CC_SHIFT) |
123 		    AHCI_CCCC_EN);
124 		ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
125 		    AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
126 		if (bootverbose) {
127 			device_printf(dev,
128 			    "CCC with %dms/4cmd enabled on vector %d\n",
129 			    ctlr->ccc, ctlr->cccv);
130 		}
131 	}
132 	/* Enable AHCI interrupts */
133 	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
134 	    ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
135 	return (0);
136 }
137 
138 int
139 ahci_ctlr_reset(device_t dev)
140 {
141 	struct ahci_controller *ctlr = device_get_softc(dev);
142 	uint32_t v;
143 	int timeout;
144 
145 	/* BIOS/OS Handoff */
146 	if ((ATA_INL(ctlr->r_mem, AHCI_VS) >= 0x00010200) &&
147 	    (ATA_INL(ctlr->r_mem, AHCI_CAP2) & AHCI_CAP2_BOH) &&
148 	    ((v = ATA_INL(ctlr->r_mem, AHCI_BOHC)) & AHCI_BOHC_OOS) == 0) {
149 		/* Request OS ownership. */
150 		ATA_OUTL(ctlr->r_mem, AHCI_BOHC, v | AHCI_BOHC_OOS);
151 
152 		/* Wait up to 2s for BIOS ownership release. */
153 		for (timeout = 0; timeout < 80; timeout++) {
154 			DELAY(25000);
155 			v = ATA_INL(ctlr->r_mem, AHCI_BOHC);
156 			if ((v & AHCI_BOHC_BOS) == 0)
157 				break;
158 			if ((v & AHCI_BOHC_BB) == 0)
159 				break;
160 		}
161 	}
162 
163 	/* Enable AHCI mode */
164 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
165 	/* Reset AHCI controller */
166 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
167 	for (timeout = 1000; timeout > 0; timeout--) {
168 		DELAY(1000);
169 		if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
170 			break;
171 	}
172 	if (timeout == 0) {
173 		device_printf(dev, "AHCI controller reset failure\n");
174 		return (ENXIO);
175 	}
176 	/* Reenable AHCI mode */
177 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
178 
179 	if (ctlr->quirks & AHCI_Q_RESTORE_CAP) {
180 		/*
181 		 * Restore capability field.
182 		 * This is write to a read-only register to restore its state.
183 		 * On fully standard-compliant hardware this is not needed and
184 		 * this operation shall not take place. See ahci_pci.c for
185 		 * platforms using this quirk.
186 		 */
187 		ATA_OUTL(ctlr->r_mem, AHCI_CAP, ctlr->caps);
188 	}
189 
190 	return (0);
191 }
192 
193 int
194 ahci_attach(device_t dev)
195 {
196 	struct ahci_controller *ctlr = device_get_softc(dev);
197 	int error, i, speed, unit;
198 	uint32_t u, version;
199 	device_t child;
200 
201 	ctlr->dev = dev;
202 	ctlr->ccc = 0;
203 	resource_int_value(device_get_name(dev),
204 	    device_get_unit(dev), "ccc", &ctlr->ccc);
205 	mtx_init(&ctlr->ch_mtx, "AHCI channels lock", NULL, MTX_DEF);
206 
207 	/* Setup our own memory management for channels. */
208 	ctlr->sc_iomem.rm_start = rman_get_start(ctlr->r_mem);
209 	ctlr->sc_iomem.rm_end = rman_get_end(ctlr->r_mem);
210 	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
211 	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
212 	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
213 		ahci_free_mem(dev);
214 		return (error);
215 	}
216 	if ((error = rman_manage_region(&ctlr->sc_iomem,
217 	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
218 		ahci_free_mem(dev);
219 		rman_fini(&ctlr->sc_iomem);
220 		return (error);
221 	}
222 	/* Get the HW capabilities */
223 	version = ATA_INL(ctlr->r_mem, AHCI_VS);
224 	ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
225 	if (version >= 0x00010200)
226 		ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
227 	if (ctlr->caps & AHCI_CAP_EMS)
228 		ctlr->capsem = ATA_INL(ctlr->r_mem, AHCI_EM_CTL);
229 
230 	if (ctlr->quirks & AHCI_Q_FORCE_PI) {
231 		/*
232 		 * Enable ports.
233 		 * The spec says that BIOS sets up bits corresponding to
234 		 * available ports. On platforms where this information
235 		 * is missing, the driver can define available ports on its own.
236 		 */
237 		int nports = (ctlr->caps & AHCI_CAP_NPMASK) + 1;
238 		int nmask = (1 << nports) - 1;
239 
240 		ATA_OUTL(ctlr->r_mem, AHCI_PI, nmask);
241 		device_printf(dev, "Forcing PI to %d ports (mask = %x)\n",
242 		    nports, nmask);
243 	}
244 
245 	ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
246 
247 	/* Identify and set separate quirks for HBA and RAID f/w Marvells. */
248 	if ((ctlr->quirks & AHCI_Q_ALTSIG) &&
249 	    (ctlr->caps & AHCI_CAP_SPM) == 0)
250 		ctlr->quirks |= AHCI_Q_NOBSYRES;
251 
252 	if (ctlr->quirks & AHCI_Q_1CH) {
253 		ctlr->caps &= ~AHCI_CAP_NPMASK;
254 		ctlr->ichannels &= 0x01;
255 	}
256 	if (ctlr->quirks & AHCI_Q_2CH) {
257 		ctlr->caps &= ~AHCI_CAP_NPMASK;
258 		ctlr->caps |= 1;
259 		ctlr->ichannels &= 0x03;
260 	}
261 	if (ctlr->quirks & AHCI_Q_4CH) {
262 		ctlr->caps &= ~AHCI_CAP_NPMASK;
263 		ctlr->caps |= 3;
264 		ctlr->ichannels &= 0x0f;
265 	}
266 	ctlr->channels = MAX(flsl(ctlr->ichannels),
267 	    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
268 	if (ctlr->quirks & AHCI_Q_NOPMP)
269 		ctlr->caps &= ~AHCI_CAP_SPM;
270 	if (ctlr->quirks & AHCI_Q_NONCQ)
271 		ctlr->caps &= ~AHCI_CAP_SNCQ;
272 	if ((ctlr->caps & AHCI_CAP_CCCS) == 0)
273 		ctlr->ccc = 0;
274 	ctlr->emloc = ATA_INL(ctlr->r_mem, AHCI_EM_LOC);
275 
276 	/* Create controller-wide DMA tag. */
277 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
278 	    (ctlr->caps & AHCI_CAP_64BIT) ? BUS_SPACE_MAXADDR :
279 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
280 	    BUS_SPACE_MAXSIZE, BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE,
281 	    ctlr->dma_coherent ? BUS_DMA_COHERENT : 0, NULL, NULL,
282 	    &ctlr->dma_tag)) {
283 		ahci_free_mem(dev);
284 		rman_fini(&ctlr->sc_iomem);
285 		return (ENXIO);
286 	}
287 
288 	ahci_ctlr_setup(dev);
289 
290 	/* Setup interrupts. */
291 	if ((error = ahci_setup_interrupt(dev)) != 0) {
292 		bus_dma_tag_destroy(ctlr->dma_tag);
293 		ahci_free_mem(dev);
294 		rman_fini(&ctlr->sc_iomem);
295 		return (error);
296 	}
297 
298 	i = 0;
299 	for (u = ctlr->ichannels; u != 0; u >>= 1)
300 		i += (u & 1);
301 	ctlr->direct = (ctlr->msi && (ctlr->numirqs > 1 || i <= 3));
302 	resource_int_value(device_get_name(dev), device_get_unit(dev),
303 	    "direct", &ctlr->direct);
304 	/* Announce HW capabilities. */
305 	speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
306 	device_printf(dev,
307 		    "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s%s\n",
308 		    ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
309 		    ((version >> 4) & 0xf0) + (version & 0x0f),
310 		    (ctlr->caps & AHCI_CAP_NPMASK) + 1,
311 		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
312 		    ((speed == 3) ? "6":"?"))),
313 		    (ctlr->caps & AHCI_CAP_SPM) ?
314 		    "supported" : "not supported",
315 		    (ctlr->caps & AHCI_CAP_FBSS) ?
316 		    " with FBS" : "");
317 	if (ctlr->quirks != 0) {
318 		device_printf(dev, "quirks=0x%b\n", ctlr->quirks,
319 		    AHCI_Q_BIT_STRING);
320 	}
321 	if (bootverbose) {
322 		device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
323 		    (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
324 		    (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
325 		    (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
326 		    (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
327 		    (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
328 		    (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
329 		    (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
330 		    (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
331 		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
332 		    ((speed == 3) ? "6":"?"))));
333 		printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
334 		    (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
335 		    (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
336 		    (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
337 		    (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
338 		    (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
339 		    (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
340 		    ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
341 		    (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
342 		    (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
343 		    (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
344 		    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
345 	}
346 	if (bootverbose && version >= 0x00010200) {
347 		device_printf(dev, "Caps2:%s%s%s%s%s%s\n",
348 		    (ctlr->caps2 & AHCI_CAP2_DESO) ? " DESO":"",
349 		    (ctlr->caps2 & AHCI_CAP2_SADM) ? " SADM":"",
350 		    (ctlr->caps2 & AHCI_CAP2_SDS) ? " SDS":"",
351 		    (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
352 		    (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
353 		    (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
354 	}
355 	/* Attach all channels on this controller */
356 	for (unit = 0; unit < ctlr->channels; unit++) {
357 		child = device_add_child(dev, "ahcich", -1);
358 		if (child == NULL) {
359 			device_printf(dev, "failed to add channel device\n");
360 			continue;
361 		}
362 		device_set_ivars(child, (void *)(intptr_t)unit);
363 		if ((ctlr->ichannels & (1 << unit)) == 0)
364 			device_disable(child);
365 	}
366 	/* Attach any remapped NVME device */
367 	for (; unit < ctlr->channels + ctlr->remapped_devices; unit++) {
368 		child = device_add_child(dev, "nvme", -1);
369 		if (child == NULL) {
370 			device_printf(dev, "failed to add remapped NVMe device");
371 			    continue;
372 		}
373 		device_set_ivars(child, (void *)(intptr_t)(unit | AHCI_REMAPPED_UNIT));
374 	}
375 
376 	int em = (ctlr->caps & AHCI_CAP_EMS) != 0;
377 	resource_int_value(device_get_name(dev), device_get_unit(dev),
378 	    "em", &em);
379 	if (em) {
380 		child = device_add_child(dev, "ahciem", -1);
381 		if (child == NULL)
382 			device_printf(dev, "failed to add enclosure device\n");
383 		else
384 			device_set_ivars(child, (void *)(intptr_t)AHCI_EM_UNIT);
385 	}
386 	bus_generic_attach(dev);
387 	return (0);
388 }
389 
390 int
391 ahci_detach(device_t dev)
392 {
393 	struct ahci_controller *ctlr = device_get_softc(dev);
394 	int i;
395 
396 	/* Detach & delete all children */
397 	device_delete_children(dev);
398 
399 	/* Free interrupts. */
400 	for (i = 0; i < ctlr->numirqs; i++) {
401 		if (ctlr->irqs[i].r_irq) {
402 			bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
403 			    ctlr->irqs[i].handle);
404 			bus_release_resource(dev, SYS_RES_IRQ,
405 			    ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
406 		}
407 	}
408 	bus_dma_tag_destroy(ctlr->dma_tag);
409 	/* Free memory. */
410 	rman_fini(&ctlr->sc_iomem);
411 	ahci_free_mem(dev);
412 	mtx_destroy(&ctlr->ch_mtx);
413 	return (0);
414 }
415 
416 void
417 ahci_free_mem(device_t dev)
418 {
419 	struct ahci_controller *ctlr = device_get_softc(dev);
420 
421 	/* Release memory resources */
422 	if (ctlr->r_mem)
423 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
424 	if (ctlr->r_msix_table)
425 		bus_release_resource(dev, SYS_RES_MEMORY,
426 		    ctlr->r_msix_tab_rid, ctlr->r_msix_table);
427 	if (ctlr->r_msix_pba)
428 		bus_release_resource(dev, SYS_RES_MEMORY,
429 		    ctlr->r_msix_pba_rid, ctlr->r_msix_pba);
430 
431 	ctlr->r_msix_pba = ctlr->r_mem = ctlr->r_msix_table = NULL;
432 }
433 
434 int
435 ahci_setup_interrupt(device_t dev)
436 {
437 	struct ahci_controller *ctlr = device_get_softc(dev);
438 	int i;
439 
440 	/* Check for single MSI vector fallback. */
441 	if (ctlr->numirqs > 1 &&
442 	    (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
443 		device_printf(dev, "Falling back to one MSI\n");
444 		ctlr->numirqs = 1;
445 	}
446 
447 	/* Ensure we don't overrun irqs. */
448 	if (ctlr->numirqs > AHCI_MAX_IRQS) {
449 		device_printf(dev, "Too many irqs %d > %d (clamping)\n",
450 		    ctlr->numirqs, AHCI_MAX_IRQS);
451 		ctlr->numirqs = AHCI_MAX_IRQS;
452 	}
453 
454 	/* Allocate all IRQs. */
455 	for (i = 0; i < ctlr->numirqs; i++) {
456 		ctlr->irqs[i].ctlr = ctlr;
457 		ctlr->irqs[i].r_irq_rid = i + (ctlr->msi ? 1 : 0);
458 		if (ctlr->channels == 1 && !ctlr->ccc && ctlr->msi)
459 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
460 		else if (ctlr->numirqs == 1 || i >= ctlr->channels ||
461 		    (ctlr->ccc && i == ctlr->cccv))
462 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
463 		else if (ctlr->channels > ctlr->numirqs &&
464 		    i == ctlr->numirqs - 1)
465 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
466 		else
467 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
468 		if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
469 		    &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
470 			device_printf(dev, "unable to map interrupt\n");
471 			return (ENXIO);
472 		}
473 		if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
474 		    (ctlr->irqs[i].mode != AHCI_IRQ_MODE_ONE) ? ahci_intr :
475 		     ((ctlr->quirks & AHCI_Q_EDGEIS) ? ahci_intr_one_edge :
476 		      ahci_intr_one),
477 		    &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
478 			/* SOS XXX release r_irq */
479 			device_printf(dev, "unable to setup interrupt\n");
480 			return (ENXIO);
481 		}
482 		if (ctlr->numirqs > 1) {
483 			bus_describe_intr(dev, ctlr->irqs[i].r_irq,
484 			    ctlr->irqs[i].handle,
485 			    ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE ?
486 			    "ch%d" : "%d", i);
487 		}
488 	}
489 	return (0);
490 }
491 
492 /*
493  * Common case interrupt handler.
494  */
495 static void
496 ahci_intr(void *data)
497 {
498 	struct ahci_controller_irq *irq = data;
499 	struct ahci_controller *ctlr = irq->ctlr;
500 	u_int32_t is, ise = 0;
501 	void *arg;
502 	int unit;
503 
504 	if (irq->mode == AHCI_IRQ_MODE_ALL) {
505 		unit = 0;
506 		if (ctlr->ccc)
507 			is = ctlr->ichannels;
508 		else
509 			is = ATA_INL(ctlr->r_mem, AHCI_IS);
510 	} else {	/* AHCI_IRQ_MODE_AFTER */
511 		unit = irq->r_irq_rid - 1;
512 		is = ATA_INL(ctlr->r_mem, AHCI_IS);
513 		is &= (0xffffffff << unit);
514 	}
515 	/* CCC interrupt is edge triggered. */
516 	if (ctlr->ccc)
517 		ise = 1 << ctlr->cccv;
518 	/* Some controllers have edge triggered IS. */
519 	if (ctlr->quirks & AHCI_Q_EDGEIS)
520 		ise |= is;
521 	if (ise != 0)
522 		ATA_OUTL(ctlr->r_mem, AHCI_IS, ise);
523 	for (; unit < ctlr->channels; unit++) {
524 		if ((is & (1 << unit)) != 0 &&
525 		    (arg = ctlr->interrupt[unit].argument)) {
526 				ctlr->interrupt[unit].function(arg);
527 		}
528 	}
529 	for (; unit < ctlr->channels + ctlr->remapped_devices; unit++) {
530 		if ((arg = ctlr->interrupt[unit].argument)) {
531 			ctlr->interrupt[unit].function(arg);
532 		}
533 	}
534 
535 	/* AHCI declares level triggered IS. */
536 	if (!(ctlr->quirks & AHCI_Q_EDGEIS))
537 		ATA_OUTL(ctlr->r_mem, AHCI_IS, is);
538 	ATA_RBL(ctlr->r_mem, AHCI_IS);
539 }
540 
541 /*
542  * Simplified interrupt handler for multivector MSI mode.
543  */
544 static void
545 ahci_intr_one(void *data)
546 {
547 	struct ahci_controller_irq *irq = data;
548 	struct ahci_controller *ctlr = irq->ctlr;
549 	void *arg;
550 	int unit;
551 
552 	unit = irq->r_irq_rid - 1;
553 	if ((arg = ctlr->interrupt[unit].argument))
554 	    ctlr->interrupt[unit].function(arg);
555 	/* AHCI declares level triggered IS. */
556 	ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
557 	ATA_RBL(ctlr->r_mem, AHCI_IS);
558 }
559 
560 static void
561 ahci_intr_one_edge(void *data)
562 {
563 	struct ahci_controller_irq *irq = data;
564 	struct ahci_controller *ctlr = irq->ctlr;
565 	void *arg;
566 	int unit;
567 
568 	unit = irq->r_irq_rid - 1;
569 	/* Some controllers have edge triggered IS. */
570 	ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
571 	if ((arg = ctlr->interrupt[unit].argument))
572 		ctlr->interrupt[unit].function(arg);
573 	ATA_RBL(ctlr->r_mem, AHCI_IS);
574 }
575 
576 struct resource *
577 ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
578     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
579 {
580 	struct ahci_controller *ctlr = device_get_softc(dev);
581 	struct resource *res;
582 	rman_res_t st;
583 	int offset, size, unit;
584 	bool is_em, is_remapped;
585 
586 	unit = (intptr_t)device_get_ivars(child);
587 	is_em = is_remapped = false;
588 	if (unit & AHCI_REMAPPED_UNIT) {
589 		unit &= AHCI_UNIT;
590 		unit -= ctlr->channels;
591 		is_remapped = true;
592 	} else if (unit & AHCI_EM_UNIT) {
593 		unit &= AHCI_UNIT;
594 		is_em = true;
595 	}
596 	res = NULL;
597 	switch (type) {
598 	case SYS_RES_MEMORY:
599 		if (is_remapped) {
600 			offset = ctlr->remap_offset + unit * ctlr->remap_size;
601 			size = ctlr->remap_size;
602 		} else if (!is_em) {
603 			offset = AHCI_OFFSET + (unit << 7);
604 			size = 128;
605 		} else if ((ctlr->caps & AHCI_CAP_EMS) == 0) {
606 			break;
607 		} else if (*rid == 0) {
608 			offset = AHCI_EM_CTL;
609 			size = 4;
610 		} else {
611 			offset = (ctlr->emloc & 0xffff0000) >> 14;
612 			size = (ctlr->emloc & 0x0000ffff) << 2;
613 			if (*rid != 1) {
614 				if (*rid == 2 && (ctlr->capsem &
615 				    (AHCI_EM_XMT | AHCI_EM_SMB)) == 0)
616 					offset += size;
617 				else
618 					break;
619 			}
620 		}
621 		st = rman_get_start(ctlr->r_mem);
622 		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
623 		    st + offset + size - 1, size, RF_ACTIVE, child);
624 		if (res) {
625 			bus_space_handle_t bsh;
626 			bus_space_tag_t bst;
627 			bsh = rman_get_bushandle(ctlr->r_mem);
628 			bst = rman_get_bustag(ctlr->r_mem);
629 			bus_space_subregion(bst, bsh, offset, 128, &bsh);
630 			rman_set_bushandle(res, bsh);
631 			rman_set_bustag(res, bst);
632 		}
633 		break;
634 	case SYS_RES_IRQ:
635 		if (*rid == ATA_IRQ_RID)
636 			res = ctlr->irqs[0].r_irq;
637 		break;
638 	}
639 	return (res);
640 }
641 
642 int
643 ahci_release_resource(device_t dev, device_t child, int type, int rid,
644     struct resource *r)
645 {
646 
647 	switch (type) {
648 	case SYS_RES_MEMORY:
649 		rman_release_resource(r);
650 		return (0);
651 	case SYS_RES_IRQ:
652 		if (rid != ATA_IRQ_RID)
653 			return (ENOENT);
654 		return (0);
655 	}
656 	return (EINVAL);
657 }
658 
659 int
660 ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
661     int flags, driver_filter_t *filter, driver_intr_t *function,
662     void *argument, void **cookiep)
663 {
664 	struct ahci_controller *ctlr = device_get_softc(dev);
665 	int unit = (intptr_t)device_get_ivars(child) & AHCI_UNIT;
666 
667 	if (filter != NULL) {
668 		printf("ahci.c: we cannot use a filter here\n");
669 		return (EINVAL);
670 	}
671 	ctlr->interrupt[unit].function = function;
672 	ctlr->interrupt[unit].argument = argument;
673 	return (0);
674 }
675 
676 int
677 ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
678     void *cookie)
679 {
680 	struct ahci_controller *ctlr = device_get_softc(dev);
681 	int unit = (intptr_t)device_get_ivars(child) & AHCI_UNIT;
682 
683 	ctlr->interrupt[unit].function = NULL;
684 	ctlr->interrupt[unit].argument = NULL;
685 	return (0);
686 }
687 
688 int
689 ahci_print_child(device_t dev, device_t child)
690 {
691 	intptr_t ivars;
692 	int retval;
693 
694 	retval = bus_print_child_header(dev, child);
695 	ivars = (intptr_t)device_get_ivars(child);
696 	if ((ivars & AHCI_EM_UNIT) == 0)
697 		retval += printf(" at channel %d", (int)ivars & AHCI_UNIT);
698 	retval += bus_print_child_footer(dev, child);
699 	return (retval);
700 }
701 
702 int
703 ahci_child_location(device_t dev, device_t child, struct sbuf *sb)
704 {
705 	intptr_t ivars;
706 
707 	ivars = (intptr_t)device_get_ivars(child);
708 	if ((ivars & AHCI_EM_UNIT) == 0)
709 		sbuf_printf(sb, "channel=%d", (int)ivars & AHCI_UNIT);
710 	return (0);
711 }
712 
713 bus_dma_tag_t
714 ahci_get_dma_tag(device_t dev, device_t child)
715 {
716 	struct ahci_controller *ctlr = device_get_softc(dev);
717 
718 	return (ctlr->dma_tag);
719 }
720 
721 void
722 ahci_attached(device_t dev, struct ahci_channel *ch)
723 {
724 	struct ahci_controller *ctlr = device_get_softc(dev);
725 
726 	mtx_lock(&ctlr->ch_mtx);
727 	ctlr->ch[ch->unit] = ch;
728 	mtx_unlock(&ctlr->ch_mtx);
729 }
730 
731 void
732 ahci_detached(device_t dev, struct ahci_channel *ch)
733 {
734 	struct ahci_controller *ctlr = device_get_softc(dev);
735 
736 	mtx_lock(&ctlr->ch_mtx);
737 	mtx_lock(&ch->mtx);
738 	ctlr->ch[ch->unit] = NULL;
739 	mtx_unlock(&ch->mtx);
740 	mtx_unlock(&ctlr->ch_mtx);
741 }
742 
743 struct ahci_channel *
744 ahci_getch(device_t dev, int n)
745 {
746 	struct ahci_controller *ctlr = device_get_softc(dev);
747 	struct ahci_channel *ch;
748 
749 	KASSERT(n >= 0 && n < AHCI_MAX_PORTS, ("Bad channel number %d", n));
750 	mtx_lock(&ctlr->ch_mtx);
751 	ch = ctlr->ch[n];
752 	if (ch != NULL)
753 		mtx_lock(&ch->mtx);
754 	mtx_unlock(&ctlr->ch_mtx);
755 	return (ch);
756 }
757 
758 void
759 ahci_putch(struct ahci_channel *ch)
760 {
761 
762 	mtx_unlock(&ch->mtx);
763 }
764 
765 static int
766 ahci_ch_probe(device_t dev)
767 {
768 
769 	device_set_desc_copy(dev, "AHCI channel");
770 	return (BUS_PROBE_DEFAULT);
771 }
772 
773 static int
774 ahci_ch_disablephy_proc(SYSCTL_HANDLER_ARGS)
775 {
776 	struct ahci_channel *ch;
777 	int error, value;
778 
779 	ch = arg1;
780 	value = ch->disablephy;
781 	error = sysctl_handle_int(oidp, &value, 0, req);
782 	if (error != 0 || req->newptr == NULL || (value != 0 && value != 1))
783 		return (error);
784 
785 	mtx_lock(&ch->mtx);
786 	ch->disablephy = value;
787 	if (value) {
788 		ahci_ch_deinit(ch->dev);
789 	} else {
790 		ahci_ch_init(ch->dev);
791 		ahci_phy_check_events(ch, ATA_SE_PHY_CHANGED | ATA_SE_EXCHANGED);
792 	}
793 	mtx_unlock(&ch->mtx);
794 
795 	return (0);
796 }
797 
798 static int
799 ahci_ch_attach(device_t dev)
800 {
801 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
802 	struct ahci_channel *ch = device_get_softc(dev);
803 	struct cam_devq *devq;
804 	struct sysctl_ctx_list *ctx;
805 	struct sysctl_oid *tree;
806 	int rid, error, i, sata_rev = 0;
807 	u_int32_t version;
808 
809 	ch->dev = dev;
810 	ch->unit = (intptr_t)device_get_ivars(dev);
811 	ch->caps = ctlr->caps;
812 	ch->caps2 = ctlr->caps2;
813 	ch->start = ctlr->ch_start;
814 	ch->quirks = ctlr->quirks;
815 	ch->vendorid = ctlr->vendorid;
816 	ch->deviceid = ctlr->deviceid;
817 	ch->subvendorid = ctlr->subvendorid;
818 	ch->subdeviceid = ctlr->subdeviceid;
819 	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1;
820 	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
821 	ch->pm_level = 0;
822 	resource_int_value(device_get_name(dev),
823 	    device_get_unit(dev), "pm_level", &ch->pm_level);
824 	STAILQ_INIT(&ch->doneq);
825 	if (ch->pm_level > 3)
826 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
827 	callout_init_mtx(&ch->reset_timer, &ch->mtx, 0);
828 	/* JMicron external ports (0) sometimes limited */
829 	if ((ctlr->quirks & AHCI_Q_SATA1_UNIT0) && ch->unit == 0)
830 		sata_rev = 1;
831 	if (ch->quirks & AHCI_Q_SATA2)
832 		sata_rev = 2;
833 	resource_int_value(device_get_name(dev),
834 	    device_get_unit(dev), "sata_rev", &sata_rev);
835 	for (i = 0; i < 16; i++) {
836 		ch->user[i].revision = sata_rev;
837 		ch->user[i].mode = 0;
838 		ch->user[i].bytecount = 8192;
839 		ch->user[i].tags = ch->numslots;
840 		ch->user[i].caps = 0;
841 		ch->curr[i] = ch->user[i];
842 		if (ch->pm_level) {
843 			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
844 			    CTS_SATA_CAPS_H_APST |
845 			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
846 		}
847 		ch->user[i].caps |= CTS_SATA_CAPS_H_DMAAA |
848 		    CTS_SATA_CAPS_H_AN;
849 	}
850 	rid = 0;
851 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
852 	    &rid, RF_ACTIVE)))
853 		return (ENXIO);
854 	ch->chcaps = ATA_INL(ch->r_mem, AHCI_P_CMD);
855 	version = ATA_INL(ctlr->r_mem, AHCI_VS);
856 	if (version < 0x00010200 && (ctlr->caps & AHCI_CAP_FBSS))
857 		ch->chcaps |= AHCI_P_CMD_FBSCP;
858 	if (ch->caps2 & AHCI_CAP2_SDS)
859 		ch->chscaps = ATA_INL(ch->r_mem, AHCI_P_DEVSLP);
860 	if (bootverbose) {
861 		device_printf(dev, "Caps:%s%s%s%s%s%s\n",
862 		    (ch->chcaps & AHCI_P_CMD_HPCP) ? " HPCP":"",
863 		    (ch->chcaps & AHCI_P_CMD_MPSP) ? " MPSP":"",
864 		    (ch->chcaps & AHCI_P_CMD_CPD) ? " CPD":"",
865 		    (ch->chcaps & AHCI_P_CMD_ESP) ? " ESP":"",
866 		    (ch->chcaps & AHCI_P_CMD_FBSCP) ? " FBSCP":"",
867 		    (ch->chscaps & AHCI_P_DEVSLP_DSP) ? " DSP":"");
868 	}
869 	ahci_dmainit(dev);
870 	ahci_slotsalloc(dev);
871 	mtx_lock(&ch->mtx);
872 	ahci_ch_init(dev);
873 	rid = ATA_IRQ_RID;
874 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
875 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
876 		device_printf(dev, "Unable to map interrupt\n");
877 		error = ENXIO;
878 		goto err0;
879 	}
880 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
881 	    ctlr->direct ? ahci_ch_intr_direct : ahci_ch_intr,
882 	    ch, &ch->ih))) {
883 		device_printf(dev, "Unable to setup interrupt\n");
884 		error = ENXIO;
885 		goto err1;
886 	}
887 	/* Create the device queue for our SIM. */
888 	devq = cam_simq_alloc(ch->numslots);
889 	if (devq == NULL) {
890 		device_printf(dev, "Unable to allocate simq\n");
891 		error = ENOMEM;
892 		goto err1;
893 	}
894 	/* Construct SIM entry */
895 	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
896 	    device_get_unit(dev), (struct mtx *)&ch->mtx,
897 	    (ch->quirks & AHCI_Q_NOCCS) ? 1 : min(2, ch->numslots),
898 	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
899 	    devq);
900 	if (ch->sim == NULL) {
901 		cam_simq_free(devq);
902 		device_printf(dev, "unable to allocate sim\n");
903 		error = ENOMEM;
904 		goto err1;
905 	}
906 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
907 		device_printf(dev, "unable to register xpt bus\n");
908 		error = ENXIO;
909 		goto err2;
910 	}
911 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
912 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
913 		device_printf(dev, "unable to create path\n");
914 		error = ENXIO;
915 		goto err3;
916 	}
917 	if (ch->pm_level > 3) {
918 		callout_reset(&ch->pm_timer,
919 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
920 		    ahci_ch_pm, ch);
921 	}
922 	mtx_unlock(&ch->mtx);
923 	ahci_attached(device_get_parent(dev), ch);
924 	ctx = device_get_sysctl_ctx(dev);
925 	tree = device_get_sysctl_tree(dev);
926 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "disable_phy",
927 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, ch,
928 	    0, ahci_ch_disablephy_proc, "IU", "Disable PHY");
929 	return (0);
930 
931 err3:
932 	xpt_bus_deregister(cam_sim_path(ch->sim));
933 err2:
934 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
935 err1:
936 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
937 err0:
938 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
939 	mtx_unlock(&ch->mtx);
940 	mtx_destroy(&ch->mtx);
941 	return (error);
942 }
943 
944 static int
945 ahci_ch_detach(device_t dev)
946 {
947 	struct ahci_channel *ch = device_get_softc(dev);
948 
949 	ahci_detached(device_get_parent(dev), ch);
950 	mtx_lock(&ch->mtx);
951 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
952 	/* Forget about reset. */
953 	if (ch->resetting) {
954 		ch->resetting = 0;
955 		xpt_release_simq(ch->sim, TRUE);
956 	}
957 	xpt_free_path(ch->path);
958 	xpt_bus_deregister(cam_sim_path(ch->sim));
959 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
960 	mtx_unlock(&ch->mtx);
961 
962 	if (ch->pm_level > 3)
963 		callout_drain(&ch->pm_timer);
964 	callout_drain(&ch->reset_timer);
965 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
966 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
967 
968 	ahci_ch_deinit(dev);
969 	ahci_slotsfree(dev);
970 	ahci_dmafini(dev);
971 
972 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
973 	mtx_destroy(&ch->mtx);
974 	return (0);
975 }
976 
977 static int
978 ahci_ch_init(device_t dev)
979 {
980 	struct ahci_channel *ch = device_get_softc(dev);
981 	uint64_t work;
982 
983 	/* Disable port interrupts */
984 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
985 	/* Setup work areas */
986 	work = ch->dma.work_bus + AHCI_CL_OFFSET;
987 	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
988 	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
989 	work = ch->dma.rfis_bus;
990 	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
991 	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
992 	/* Activate the channel and power/spin up device */
993 	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
994 	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
995 	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
996 	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
997 	ahci_start_fr(ch);
998 	ahci_start(ch, 1);
999 	return (0);
1000 }
1001 
1002 static int
1003 ahci_ch_deinit(device_t dev)
1004 {
1005 	struct ahci_channel *ch = device_get_softc(dev);
1006 
1007 	/* Disable port interrupts. */
1008 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1009 	/* Reset command register. */
1010 	ahci_stop(ch);
1011 	ahci_stop_fr(ch);
1012 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
1013 	/* Allow everything, including partial and slumber modes. */
1014 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
1015 	/* Request slumber mode transition and give some time to get there. */
1016 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
1017 	DELAY(100);
1018 	/* Disable PHY. */
1019 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
1020 	return (0);
1021 }
1022 
1023 static int
1024 ahci_ch_suspend(device_t dev)
1025 {
1026 	struct ahci_channel *ch = device_get_softc(dev);
1027 
1028 	mtx_lock(&ch->mtx);
1029 	xpt_freeze_simq(ch->sim, 1);
1030 	/* Forget about reset. */
1031 	if (ch->resetting) {
1032 		ch->resetting = 0;
1033 		callout_stop(&ch->reset_timer);
1034 		xpt_release_simq(ch->sim, TRUE);
1035 	}
1036 	while (ch->oslots)
1037 		msleep(ch, &ch->mtx, PRIBIO, "ahcisusp", hz/100);
1038 	ahci_ch_deinit(dev);
1039 	mtx_unlock(&ch->mtx);
1040 	return (0);
1041 }
1042 
1043 static int
1044 ahci_ch_resume(device_t dev)
1045 {
1046 	struct ahci_channel *ch = device_get_softc(dev);
1047 
1048 	mtx_lock(&ch->mtx);
1049 	ahci_ch_init(dev);
1050 	ahci_reset(ch);
1051 	xpt_release_simq(ch->sim, TRUE);
1052 	mtx_unlock(&ch->mtx);
1053 	return (0);
1054 }
1055 
1056 static device_method_t ahcich_methods[] = {
1057 	DEVMETHOD(device_probe,     ahci_ch_probe),
1058 	DEVMETHOD(device_attach,    ahci_ch_attach),
1059 	DEVMETHOD(device_detach,    ahci_ch_detach),
1060 	DEVMETHOD(device_suspend,   ahci_ch_suspend),
1061 	DEVMETHOD(device_resume,    ahci_ch_resume),
1062 	DEVMETHOD_END
1063 };
1064 static driver_t ahcich_driver = {
1065         "ahcich",
1066         ahcich_methods,
1067         sizeof(struct ahci_channel)
1068 };
1069 DRIVER_MODULE(ahcich, ahci, ahcich_driver, NULL, NULL);
1070 
1071 struct ahci_dc_cb_args {
1072 	bus_addr_t maddr;
1073 	int error;
1074 };
1075 
1076 static void
1077 ahci_dmainit(device_t dev)
1078 {
1079 	struct ahci_channel *ch = device_get_softc(dev);
1080 	struct ahci_dc_cb_args dcba;
1081 	size_t rfsize;
1082 	int error;
1083 
1084 	/* Command area. */
1085 	error = bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
1086 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1087 	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
1088 	    0, NULL, NULL, &ch->dma.work_tag);
1089 	if (error != 0)
1090 		goto error;
1091 	error = bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work,
1092 	    BUS_DMA_ZERO, &ch->dma.work_map);
1093 	if (error != 0)
1094 		goto error;
1095 	error = bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
1096 	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, BUS_DMA_NOWAIT);
1097 	if (error != 0 || (error = dcba.error) != 0) {
1098 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1099 		goto error;
1100 	}
1101 	ch->dma.work_bus = dcba.maddr;
1102 	/* FIS receive area. */
1103 	if (ch->chcaps & AHCI_P_CMD_FBSCP)
1104 	    rfsize = 4096;
1105 	else
1106 	    rfsize = 256;
1107 	error = bus_dma_tag_create(bus_get_dma_tag(dev), rfsize, 0,
1108 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1109 	    NULL, NULL, rfsize, 1, rfsize,
1110 	    0, NULL, NULL, &ch->dma.rfis_tag);
1111 	if (error != 0)
1112 		goto error;
1113 	error = bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1114 	    &ch->dma.rfis_map);
1115 	if (error != 0)
1116 		goto error;
1117 	error = bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1118 	    rfsize, ahci_dmasetupc_cb, &dcba, BUS_DMA_NOWAIT);
1119 	if (error != 0 || (error = dcba.error) != 0) {
1120 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1121 		goto error;
1122 	}
1123 	ch->dma.rfis_bus = dcba.maddr;
1124 	/* Data area. */
1125 	error = bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1126 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
1127 	    NULL, NULL,
1128 	    AHCI_SG_ENTRIES * PAGE_SIZE, AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1129 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag);
1130 	if (error != 0)
1131 		goto error;
1132 	return;
1133 
1134 error:
1135 	device_printf(dev, "WARNING - DMA initialization failed, error %d\n",
1136 	    error);
1137 	ahci_dmafini(dev);
1138 }
1139 
1140 static void
1141 ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1142 {
1143 	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1144 
1145 	if (!(dcba->error = error))
1146 		dcba->maddr = segs[0].ds_addr;
1147 }
1148 
1149 static void
1150 ahci_dmafini(device_t dev)
1151 {
1152 	struct ahci_channel *ch = device_get_softc(dev);
1153 
1154 	if (ch->dma.data_tag) {
1155 		bus_dma_tag_destroy(ch->dma.data_tag);
1156 		ch->dma.data_tag = NULL;
1157 	}
1158 	if (ch->dma.rfis_bus) {
1159 		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1160 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1161 		ch->dma.rfis_bus = 0;
1162 		ch->dma.rfis = NULL;
1163 	}
1164 	if (ch->dma.work_bus) {
1165 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1166 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1167 		ch->dma.work_bus = 0;
1168 		ch->dma.work = NULL;
1169 	}
1170 	if (ch->dma.work_tag) {
1171 		bus_dma_tag_destroy(ch->dma.work_tag);
1172 		ch->dma.work_tag = NULL;
1173 	}
1174 }
1175 
1176 static void
1177 ahci_slotsalloc(device_t dev)
1178 {
1179 	struct ahci_channel *ch = device_get_softc(dev);
1180 	int i;
1181 
1182 	/* Alloc and setup command/dma slots */
1183 	bzero(ch->slot, sizeof(ch->slot));
1184 	for (i = 0; i < ch->numslots; i++) {
1185 		struct ahci_slot *slot = &ch->slot[i];
1186 
1187 		slot->ch = ch;
1188 		slot->slot = i;
1189 		slot->state = AHCI_SLOT_EMPTY;
1190 		slot->ct_offset = AHCI_CT_OFFSET + AHCI_CT_SIZE * i;
1191 		slot->ccb = NULL;
1192 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1193 
1194 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1195 			device_printf(ch->dev, "FAILURE - create data_map\n");
1196 	}
1197 }
1198 
1199 static void
1200 ahci_slotsfree(device_t dev)
1201 {
1202 	struct ahci_channel *ch = device_get_softc(dev);
1203 	int i;
1204 
1205 	/* Free all dma slots */
1206 	for (i = 0; i < ch->numslots; i++) {
1207 		struct ahci_slot *slot = &ch->slot[i];
1208 
1209 		callout_drain(&slot->timeout);
1210 		if (slot->dma.data_map) {
1211 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1212 			slot->dma.data_map = NULL;
1213 		}
1214 	}
1215 }
1216 
1217 static int
1218 ahci_phy_check_events(struct ahci_channel *ch, u_int32_t serr)
1219 {
1220 
1221 	if (((ch->pm_level == 0) && (serr & ATA_SE_PHY_CHANGED)) ||
1222 	    ((ch->pm_level != 0 || ch->listening) && (serr & ATA_SE_EXCHANGED))) {
1223 		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1224 		union ccb *ccb;
1225 
1226 		if (bootverbose) {
1227 			if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
1228 				device_printf(ch->dev, "CONNECT requested\n");
1229 			else
1230 				device_printf(ch->dev, "DISCONNECT requested\n");
1231 		}
1232 		ahci_reset(ch);
1233 		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1234 			return (0);
1235 		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1236 		    cam_sim_path(ch->sim),
1237 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1238 			xpt_free_ccb(ccb);
1239 			return (0);
1240 		}
1241 		xpt_rescan(ccb);
1242 		return (1);
1243 	}
1244 	return (0);
1245 }
1246 
1247 static void
1248 ahci_cpd_check_events(struct ahci_channel *ch)
1249 {
1250 	u_int32_t status;
1251 	union ccb *ccb;
1252 	device_t dev;
1253 
1254 	if (ch->pm_level == 0)
1255 		return;
1256 
1257 	status = ATA_INL(ch->r_mem, AHCI_P_CMD);
1258 	if ((status & AHCI_P_CMD_CPD) == 0)
1259 		return;
1260 
1261 	if (bootverbose) {
1262 		dev = ch->dev;
1263 		if (status & AHCI_P_CMD_CPS) {
1264 			device_printf(dev, "COLD CONNECT requested\n");
1265 		} else
1266 			device_printf(dev, "COLD DISCONNECT requested\n");
1267 	}
1268 	ahci_reset(ch);
1269 	if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1270 		return;
1271 	if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(ch->sim),
1272 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1273 		xpt_free_ccb(ccb);
1274 		return;
1275 	}
1276 	xpt_rescan(ccb);
1277 }
1278 
1279 static void
1280 ahci_notify_events(struct ahci_channel *ch, u_int32_t status)
1281 {
1282 	struct cam_path *dpath;
1283 	int i;
1284 
1285 	if (ch->caps & AHCI_CAP_SSNTF)
1286 		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1287 	if (bootverbose)
1288 		device_printf(ch->dev, "SNTF 0x%04x\n", status);
1289 	for (i = 0; i < 16; i++) {
1290 		if ((status & (1 << i)) == 0)
1291 			continue;
1292 		if (xpt_create_path(&dpath, NULL,
1293 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1294 			xpt_async(AC_SCSI_AEN, dpath, NULL);
1295 			xpt_free_path(dpath);
1296 		}
1297 	}
1298 }
1299 
1300 static void
1301 ahci_done(struct ahci_channel *ch, union ccb *ccb)
1302 {
1303 
1304 	mtx_assert(&ch->mtx, MA_OWNED);
1305 	if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0 ||
1306 	    ch->batch == 0) {
1307 		xpt_done(ccb);
1308 		return;
1309 	}
1310 
1311 	STAILQ_INSERT_TAIL(&ch->doneq, &ccb->ccb_h, sim_links.stqe);
1312 }
1313 
1314 static void
1315 ahci_ch_intr(void *arg)
1316 {
1317 	struct ahci_channel *ch = (struct ahci_channel *)arg;
1318 	uint32_t istatus;
1319 
1320 	/* Read interrupt statuses. */
1321 	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1322 
1323 	mtx_lock(&ch->mtx);
1324 	ahci_ch_intr_main(ch, istatus);
1325 	mtx_unlock(&ch->mtx);
1326 }
1327 
1328 static void
1329 ahci_ch_intr_direct(void *arg)
1330 {
1331 	struct ahci_channel *ch = (struct ahci_channel *)arg;
1332 	struct ccb_hdr *ccb_h;
1333 	uint32_t istatus;
1334 	STAILQ_HEAD(, ccb_hdr) tmp_doneq = STAILQ_HEAD_INITIALIZER(tmp_doneq);
1335 
1336 	/* Read interrupt statuses. */
1337 	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1338 
1339 	mtx_lock(&ch->mtx);
1340 	ch->batch = 1;
1341 	ahci_ch_intr_main(ch, istatus);
1342 	ch->batch = 0;
1343 	/*
1344 	 * Prevent the possibility of issues caused by processing the queue
1345 	 * while unlocked below by moving the contents to a local queue.
1346 	 */
1347 	STAILQ_CONCAT(&tmp_doneq, &ch->doneq);
1348 	mtx_unlock(&ch->mtx);
1349 	while ((ccb_h = STAILQ_FIRST(&tmp_doneq)) != NULL) {
1350 		STAILQ_REMOVE_HEAD(&tmp_doneq, sim_links.stqe);
1351 		xpt_done_direct((union ccb *)ccb_h);
1352 	}
1353 }
1354 
1355 static void
1356 ahci_ch_pm(void *arg)
1357 {
1358 	struct ahci_channel *ch = (struct ahci_channel *)arg;
1359 	uint32_t work;
1360 
1361 	if (ch->numrslots != 0)
1362 		return;
1363 	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1364 	if (ch->pm_level == 4)
1365 		work |= AHCI_P_CMD_PARTIAL;
1366 	else
1367 		work |= AHCI_P_CMD_SLUMBER;
1368 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1369 }
1370 
1371 static void
1372 ahci_ch_intr_main(struct ahci_channel *ch, uint32_t istatus)
1373 {
1374 	uint32_t cstatus, serr = 0, sntf = 0, ok, err;
1375 	enum ahci_err_type et;
1376 	int i, ccs, port, reset = 0;
1377 
1378 	/* Clear interrupt statuses. */
1379 	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1380 	/* Read command statuses. */
1381 	if (ch->numtslots != 0)
1382 		cstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1383 	else
1384 		cstatus = 0;
1385 	if (ch->numrslots != ch->numtslots)
1386 		cstatus |= ATA_INL(ch->r_mem, AHCI_P_CI);
1387 	/* Read SNTF in one of possible ways. */
1388 	if ((istatus & AHCI_P_IX_SDB) &&
1389 	    (ch->pm_present || ch->curr[0].atapi != 0)) {
1390 		if (ch->caps & AHCI_CAP_SSNTF)
1391 			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1392 		else if (ch->fbs_enabled) {
1393 			u_int8_t *fis = ch->dma.rfis + 0x58;
1394 
1395 			for (i = 0; i < 16; i++) {
1396 				if (fis[1] & 0x80) {
1397 					fis[1] &= 0x7f;
1398 	    				sntf |= 1 << i;
1399 	    			}
1400 	    			fis += 256;
1401 	    		}
1402 		} else {
1403 			u_int8_t *fis = ch->dma.rfis + 0x58;
1404 
1405 			if (fis[1] & 0x80)
1406 				sntf = (1 << (fis[1] & 0x0f));
1407 		}
1408 	}
1409 	/* Process PHY events */
1410 	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1411 	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1412 		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1413 		if (serr) {
1414 			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1415 			reset = ahci_phy_check_events(ch, serr);
1416 		}
1417 	}
1418 	/* Process cold presence detection events */
1419 	if ((istatus & AHCI_P_IX_CPD) && !reset)
1420 		ahci_cpd_check_events(ch);
1421 	/* Process command errors */
1422 	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1423 	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1424 		if (ch->quirks & AHCI_Q_NOCCS) {
1425 			/*
1426 			 * ASMedia chips sometimes report failed commands as
1427 			 * completed.  Count all running commands as failed.
1428 			 */
1429 			cstatus |= ch->rslots;
1430 
1431 			/* They also report wrong CCS, so try to guess one. */
1432 			ccs = powerof2(cstatus) ? ffs(cstatus) - 1 : -1;
1433 		} else {
1434 			ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) &
1435 			    AHCI_P_CMD_CCS_MASK) >> AHCI_P_CMD_CCS_SHIFT;
1436 		}
1437 //device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1438 //    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1439 //    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1440 		port = -1;
1441 		if (ch->fbs_enabled) {
1442 			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1443 			if (fbs & AHCI_P_FBS_SDE) {
1444 				port = (fbs & AHCI_P_FBS_DWE)
1445 				    >> AHCI_P_FBS_DWE_SHIFT;
1446 			} else {
1447 				for (i = 0; i < 16; i++) {
1448 					if (ch->numrslotspd[i] == 0)
1449 						continue;
1450 					if (port == -1)
1451 						port = i;
1452 					else if (port != i) {
1453 						port = -2;
1454 						break;
1455 					}
1456 				}
1457 			}
1458 		}
1459 		err = ch->rslots & cstatus;
1460 	} else {
1461 		ccs = 0;
1462 		err = 0;
1463 		port = -1;
1464 	}
1465 	/* Complete all successful commands. */
1466 	ok = ch->rslots & ~cstatus;
1467 	for (i = 0; i < ch->numslots; i++) {
1468 		if ((ok >> i) & 1)
1469 			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1470 	}
1471 	/* On error, complete the rest of commands with error statuses. */
1472 	if (err) {
1473 		if (ch->frozen) {
1474 			union ccb *fccb = ch->frozen;
1475 			ch->frozen = NULL;
1476 			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1477 			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1478 				xpt_freeze_devq(fccb->ccb_h.path, 1);
1479 				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1480 			}
1481 			ahci_done(ch, fccb);
1482 		}
1483 		for (i = 0; i < ch->numslots; i++) {
1484 			/* XXX: requests in loading state. */
1485 			if (((err >> i) & 1) == 0)
1486 				continue;
1487 			if (port >= 0 &&
1488 			    ch->slot[i].ccb->ccb_h.target_id != port)
1489 				continue;
1490 			if (istatus & AHCI_P_IX_TFE) {
1491 			    if (port != -2) {
1492 				/* Task File Error */
1493 				if (ch->numtslotspd[
1494 				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1495 					/* Untagged operation. */
1496 					if (i == ccs)
1497 						et = AHCI_ERR_TFE;
1498 					else
1499 						et = AHCI_ERR_INNOCENT;
1500 				} else {
1501 					/* Tagged operation. */
1502 					et = AHCI_ERR_NCQ;
1503 				}
1504 			    } else {
1505 				et = AHCI_ERR_TFE;
1506 				ch->fatalerr = 1;
1507 			    }
1508 			} else if (istatus & AHCI_P_IX_IF) {
1509 				if (ch->numtslots == 0 && i != ccs && port != -2)
1510 					et = AHCI_ERR_INNOCENT;
1511 				else
1512 					et = AHCI_ERR_SATA;
1513 			} else
1514 				et = AHCI_ERR_INVALID;
1515 			ahci_end_transaction(&ch->slot[i], et);
1516 		}
1517 		/*
1518 		 * We can't reinit port if there are some other
1519 		 * commands active, use resume to complete them.
1520 		 */
1521 		if (ch->rslots != 0 && !ch->recoverycmd)
1522 			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1523 	}
1524 	/* Process NOTIFY events */
1525 	if (sntf)
1526 		ahci_notify_events(ch, sntf);
1527 }
1528 
1529 /* Must be called with channel locked. */
1530 static int
1531 ahci_check_collision(struct ahci_channel *ch, union ccb *ccb)
1532 {
1533 	int t = ccb->ccb_h.target_id;
1534 
1535 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1536 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1537 		/* Tagged command while we have no supported tag free. */
1538 		if (((~ch->oslots) & (0xffffffff >> (32 -
1539 		    ch->curr[t].tags))) == 0)
1540 			return (1);
1541 		/* If we have FBS */
1542 		if (ch->fbs_enabled) {
1543 			/* Tagged command while untagged are active. */
1544 			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1545 				return (1);
1546 		} else {
1547 			/* Tagged command while untagged are active. */
1548 			if (ch->numrslots != 0 && ch->numtslots == 0)
1549 				return (1);
1550 			/* Tagged command while tagged to other target is active. */
1551 			if (ch->numtslots != 0 &&
1552 			    ch->taggedtarget != ccb->ccb_h.target_id)
1553 				return (1);
1554 		}
1555 	} else {
1556 		/* If we have FBS */
1557 		if (ch->fbs_enabled) {
1558 			/* Untagged command while tagged are active. */
1559 			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1560 				return (1);
1561 		} else {
1562 			/* Untagged command while tagged are active. */
1563 			if (ch->numrslots != 0 && ch->numtslots != 0)
1564 				return (1);
1565 		}
1566 	}
1567 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1568 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1569 		/* Atomic command while anything active. */
1570 		if (ch->numrslots != 0)
1571 			return (1);
1572 	}
1573        /* We have some atomic command running. */
1574        if (ch->aslots != 0)
1575                return (1);
1576 	return (0);
1577 }
1578 
1579 /* Must be called with channel locked. */
1580 static void
1581 ahci_begin_transaction(struct ahci_channel *ch, union ccb *ccb)
1582 {
1583 	struct ahci_slot *slot;
1584 	int tag, tags;
1585 
1586 	/* Choose empty slot. */
1587 	tags = ch->numslots;
1588 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1589 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1590 		tags = ch->curr[ccb->ccb_h.target_id].tags;
1591 	if (ch->lastslot + 1 < tags)
1592 		tag = ffs(~(ch->oslots >> (ch->lastslot + 1)));
1593 	else
1594 		tag = 0;
1595 	if (tag == 0 || tag + ch->lastslot >= tags)
1596 		tag = ffs(~ch->oslots) - 1;
1597 	else
1598 		tag += ch->lastslot;
1599 	ch->lastslot = tag;
1600 	/* Occupy chosen slot. */
1601 	slot = &ch->slot[tag];
1602 	slot->ccb = ccb;
1603 	/* Stop PM timer. */
1604 	if (ch->numrslots == 0 && ch->pm_level > 3)
1605 		callout_stop(&ch->pm_timer);
1606 	/* Update channel stats. */
1607 	ch->oslots |= (1 << tag);
1608 	ch->numrslots++;
1609 	ch->numrslotspd[ccb->ccb_h.target_id]++;
1610 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1611 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1612 		ch->numtslots++;
1613 		ch->numtslotspd[ccb->ccb_h.target_id]++;
1614 		ch->taggedtarget = ccb->ccb_h.target_id;
1615 	}
1616 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1617 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1618 		ch->aslots |= (1 << tag);
1619 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1620 		slot->state = AHCI_SLOT_LOADING;
1621 		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map, ccb,
1622 		    ahci_dmasetprd, slot, 0);
1623 	} else {
1624 		slot->dma.nsegs = 0;
1625 		ahci_execute_transaction(slot);
1626 	}
1627 }
1628 
1629 /* Locked by busdma engine. */
1630 static void
1631 ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1632 {
1633 	struct ahci_slot *slot = arg;
1634 	struct ahci_channel *ch = slot->ch;
1635 	struct ahci_cmd_tab *ctp;
1636 	struct ahci_dma_prd *prd;
1637 	int i;
1638 
1639 	if (error) {
1640 		device_printf(ch->dev, "DMA load error\n");
1641 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1642 		return;
1643 	}
1644 	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1645 	/* Get a piece of the workspace for this request */
1646 	ctp = (struct ahci_cmd_tab *)(ch->dma.work + slot->ct_offset);
1647 	/* Fill S/G table */
1648 	prd = &ctp->prd_tab[0];
1649 	for (i = 0; i < nsegs; i++) {
1650 		prd[i].dba = htole64(segs[i].ds_addr);
1651 		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1652 	}
1653 	slot->dma.nsegs = nsegs;
1654 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1655 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1656 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1657 	ahci_execute_transaction(slot);
1658 }
1659 
1660 /* Must be called with channel locked. */
1661 static void
1662 ahci_execute_transaction(struct ahci_slot *slot)
1663 {
1664 	struct ahci_channel *ch = slot->ch;
1665 	struct ahci_cmd_tab *ctp;
1666 	struct ahci_cmd_list *clp;
1667 	union ccb *ccb = slot->ccb;
1668 	int port = ccb->ccb_h.target_id & 0x0f;
1669 	int fis_size, i, softreset;
1670 	uint8_t *fis = ch->dma.rfis + 0x40;
1671 	uint8_t val;
1672 	uint16_t cmd_flags;
1673 
1674 	/* Get a piece of the workspace for this request */
1675 	ctp = (struct ahci_cmd_tab *)(ch->dma.work + slot->ct_offset);
1676 	/* Setup the FIS for this request */
1677 	if (!(fis_size = ahci_setup_fis(ch, ctp, ccb, slot->slot))) {
1678 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1679 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1680 		return;
1681 	}
1682 	/* Setup the command list entry */
1683 	clp = (struct ahci_cmd_list *)
1684 	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1685 	cmd_flags =
1686 		    (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1687 		    (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1688 		     (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1689 		    (fis_size / sizeof(u_int32_t)) |
1690 		    (port << 12);
1691 	clp->prd_length = htole16(slot->dma.nsegs);
1692 	/* Special handling for Soft Reset command. */
1693 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1694 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1695 		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1696 			softreset = 1;
1697 			/* Kick controller into sane state */
1698 			ahci_stop(ch);
1699 			ahci_clo(ch);
1700 			ahci_start(ch, 0);
1701 			cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1702 		} else {
1703 			softreset = 2;
1704 			/* Prepare FIS receive area for check. */
1705 			for (i = 0; i < 20; i++)
1706 				fis[i] = 0xff;
1707 		}
1708 	} else
1709 		softreset = 0;
1710 	clp->bytecount = 0;
1711 	clp->cmd_flags = htole16(cmd_flags);
1712 	clp->cmd_table_phys = htole64(ch->dma.work_bus + slot->ct_offset);
1713 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1714 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1715 	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1716 	    BUS_DMASYNC_PREREAD);
1717 	/* Set ACTIVE bit for NCQ commands. */
1718 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1719 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1720 		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1721 	}
1722 	/* If FBS is enabled, set PMP port. */
1723 	if (ch->fbs_enabled) {
1724 		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1725 		    (port << AHCI_P_FBS_DEV_SHIFT));
1726 	}
1727 	/* Issue command to the controller. */
1728 	slot->state = AHCI_SLOT_RUNNING;
1729 	ch->rslots |= (1 << slot->slot);
1730 	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1731 	/* Device reset commands doesn't interrupt. Poll them. */
1732 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1733 	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET || softreset)) {
1734 		int count, timeout = ccb->ccb_h.timeout * 100;
1735 		enum ahci_err_type et = AHCI_ERR_NONE;
1736 
1737 		for (count = 0; count < timeout; count++) {
1738 			DELAY(10);
1739 			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1740 				break;
1741 			if ((ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) &&
1742 			    softreset != 1) {
1743 #if 0
1744 				device_printf(ch->dev,
1745 				    "Poll error on slot %d, TFD: %04x\n",
1746 				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1747 #endif
1748 				et = AHCI_ERR_TFE;
1749 				break;
1750 			}
1751 			/* Workaround for ATI SB600/SB700 chipsets. */
1752 			if (ccb->ccb_h.target_id == 15 &&
1753 			    (ch->quirks & AHCI_Q_ATI_PMP_BUG) &&
1754 			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1755 				et = AHCI_ERR_TIMEOUT;
1756 				break;
1757 			}
1758 		}
1759 
1760 		/*
1761 		 * Some Marvell controllers require additional time
1762 		 * after soft reset to work properly. Setup delay
1763 		 * to 50ms after soft reset.
1764 		 */
1765 		if (ch->quirks & AHCI_Q_MRVL_SR_DEL)
1766 			DELAY(50000);
1767 
1768 		/*
1769 		 * Marvell HBAs with non-RAID firmware do not wait for
1770 		 * readiness after soft reset, so we have to wait here.
1771 		 * Marvell RAIDs do not have this problem, but instead
1772 		 * sometimes forget to update FIS receive area, breaking
1773 		 * this wait.
1774 		 */
1775 		if ((ch->quirks & AHCI_Q_NOBSYRES) == 0 &&
1776 		    (ch->quirks & AHCI_Q_ATI_PMP_BUG) == 0 &&
1777 		    softreset == 2 && et == AHCI_ERR_NONE) {
1778 			for ( ; count < timeout; count++) {
1779 				bus_dmamap_sync(ch->dma.rfis_tag,
1780 				    ch->dma.rfis_map, BUS_DMASYNC_POSTREAD);
1781 				val = fis[2];
1782 				bus_dmamap_sync(ch->dma.rfis_tag,
1783 				    ch->dma.rfis_map, BUS_DMASYNC_PREREAD);
1784 				if ((val & ATA_S_BUSY) == 0)
1785 					break;
1786 				DELAY(10);
1787 			}
1788 		}
1789 
1790 		if (timeout && (count >= timeout)) {
1791 			device_printf(ch->dev, "Poll timeout on slot %d port %d\n",
1792 			    slot->slot, port);
1793 			device_printf(ch->dev, "is %08x cs %08x ss %08x "
1794 			    "rs %08x tfd %02x serr %08x cmd %08x\n",
1795 			    ATA_INL(ch->r_mem, AHCI_P_IS),
1796 			    ATA_INL(ch->r_mem, AHCI_P_CI),
1797 			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1798 			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1799 			    ATA_INL(ch->r_mem, AHCI_P_SERR),
1800 			    ATA_INL(ch->r_mem, AHCI_P_CMD));
1801 			et = AHCI_ERR_TIMEOUT;
1802 		}
1803 
1804 		/* Kick controller into sane state and enable FBS. */
1805 		if (softreset == 2)
1806 			ch->eslots |= (1 << slot->slot);
1807 		ahci_end_transaction(slot, et);
1808 		return;
1809 	}
1810 	/* Start command execution timeout */
1811 	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout / 2,
1812 	    0, ahci_timeout, slot, 0);
1813 	return;
1814 }
1815 
1816 /* Must be called with channel locked. */
1817 static void
1818 ahci_process_timeout(struct ahci_channel *ch)
1819 {
1820 	int i;
1821 
1822 	mtx_assert(&ch->mtx, MA_OWNED);
1823 	/* Handle the rest of commands. */
1824 	for (i = 0; i < ch->numslots; i++) {
1825 		/* Do we have a running request on slot? */
1826 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1827 			continue;
1828 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1829 	}
1830 }
1831 
1832 /* Must be called with channel locked. */
1833 static void
1834 ahci_rearm_timeout(struct ahci_channel *ch)
1835 {
1836 	int i;
1837 
1838 	mtx_assert(&ch->mtx, MA_OWNED);
1839 	for (i = 0; i < ch->numslots; i++) {
1840 		struct ahci_slot *slot = &ch->slot[i];
1841 
1842 		/* Do we have a running request on slot? */
1843 		if (slot->state < AHCI_SLOT_RUNNING)
1844 			continue;
1845 		if ((ch->toslots & (1 << i)) == 0)
1846 			continue;
1847 		callout_reset_sbt(&slot->timeout,
1848     	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1849 		    ahci_timeout, slot, 0);
1850 	}
1851 }
1852 
1853 /* Locked by callout mechanism. */
1854 static void
1855 ahci_timeout(void *arg)
1856 {
1857 	struct ahci_slot *slot = arg;
1858 	struct ahci_channel *ch = slot->ch;
1859 	device_t dev = ch->dev;
1860 	uint32_t sstatus;
1861 	int ccs;
1862 	int i;
1863 
1864 	/* Check for stale timeout. */
1865 	if (slot->state < AHCI_SLOT_RUNNING)
1866 		return;
1867 
1868 	/* Check if slot was not being executed last time we checked. */
1869 	if (slot->state < AHCI_SLOT_EXECUTING) {
1870 		/* Check if slot started executing. */
1871 		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1872 		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1873 		    >> AHCI_P_CMD_CCS_SHIFT;
1874 		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1875 		    ch->fbs_enabled || ch->wrongccs)
1876 			slot->state = AHCI_SLOT_EXECUTING;
1877 		else if ((ch->rslots & (1 << ccs)) == 0) {
1878 			ch->wrongccs = 1;
1879 			slot->state = AHCI_SLOT_EXECUTING;
1880 		}
1881 
1882 		callout_reset_sbt(&slot->timeout,
1883 	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1884 		    ahci_timeout, slot, 0);
1885 		return;
1886 	}
1887 
1888 	device_printf(dev, "Timeout on slot %d port %d\n",
1889 	    slot->slot, slot->ccb->ccb_h.target_id & 0x0f);
1890 	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x "
1891 	    "serr %08x cmd %08x\n",
1892 	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1893 	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1894 	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR),
1895 	    ATA_INL(ch->r_mem, AHCI_P_CMD));
1896 
1897 	/* Handle frozen command. */
1898 	if (ch->frozen) {
1899 		union ccb *fccb = ch->frozen;
1900 		ch->frozen = NULL;
1901 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1902 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1903 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1904 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1905 		}
1906 		ahci_done(ch, fccb);
1907 	}
1908 	if (!ch->fbs_enabled && !ch->wrongccs) {
1909 		/* Without FBS we know real timeout source. */
1910 		ch->fatalerr = 1;
1911 		/* Handle command with timeout. */
1912 		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1913 		/* Handle the rest of commands. */
1914 		for (i = 0; i < ch->numslots; i++) {
1915 			/* Do we have a running request on slot? */
1916 			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1917 				continue;
1918 			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1919 		}
1920 	} else {
1921 		/* With FBS we wait for other commands timeout and pray. */
1922 		if (ch->toslots == 0)
1923 			xpt_freeze_simq(ch->sim, 1);
1924 		ch->toslots |= (1 << slot->slot);
1925 		if ((ch->rslots & ~ch->toslots) == 0)
1926 			ahci_process_timeout(ch);
1927 		else
1928 			device_printf(dev, " ... waiting for slots %08x\n",
1929 			    ch->rslots & ~ch->toslots);
1930 	}
1931 }
1932 
1933 /* Must be called with channel locked. */
1934 static void
1935 ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1936 {
1937 	struct ahci_channel *ch = slot->ch;
1938 	union ccb *ccb = slot->ccb;
1939 	struct ahci_cmd_list *clp;
1940 	int lastto;
1941 	uint32_t sig;
1942 
1943 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1944 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1945 	clp = (struct ahci_cmd_list *)
1946 	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1947 	/* Read result registers to the result struct
1948 	 * May be incorrect if several commands finished same time,
1949 	 * so read only when sure or have to.
1950 	 */
1951 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1952 		struct ata_res *res = &ccb->ataio.res;
1953 
1954 		if ((et == AHCI_ERR_TFE) ||
1955 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1956 			u_int8_t *fis = ch->dma.rfis + 0x40;
1957 
1958 			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1959 			    BUS_DMASYNC_POSTREAD);
1960 			if (ch->fbs_enabled) {
1961 				fis += ccb->ccb_h.target_id * 256;
1962 				res->status = fis[2];
1963 				res->error = fis[3];
1964 			} else {
1965 				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1966 
1967 				res->status = tfd;
1968 				res->error = tfd >> 8;
1969 			}
1970 			res->lba_low = fis[4];
1971 			res->lba_mid = fis[5];
1972 			res->lba_high = fis[6];
1973 			res->device = fis[7];
1974 			res->lba_low_exp = fis[8];
1975 			res->lba_mid_exp = fis[9];
1976 			res->lba_high_exp = fis[10];
1977 			res->sector_count = fis[12];
1978 			res->sector_count_exp = fis[13];
1979 
1980 			/*
1981 			 * Some weird controllers do not return signature in
1982 			 * FIS receive area. Read it from PxSIG register.
1983 			 */
1984 			if ((ch->quirks & AHCI_Q_ALTSIG) &&
1985 			    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1986 			    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1987 				sig = ATA_INL(ch->r_mem,  AHCI_P_SIG);
1988 				res->lba_high = sig >> 24;
1989 				res->lba_mid = sig >> 16;
1990 				res->lba_low = sig >> 8;
1991 				res->sector_count = sig;
1992 			}
1993 		} else
1994 			bzero(res, sizeof(*res));
1995 		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
1996 		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1997 		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
1998 			ccb->ataio.resid =
1999 			    ccb->ataio.dxfer_len - le32toh(clp->bytecount);
2000 		}
2001 	} else {
2002 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2003 		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
2004 			ccb->csio.resid =
2005 			    ccb->csio.dxfer_len - le32toh(clp->bytecount);
2006 		}
2007 	}
2008 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2009 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
2010 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
2011 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
2012 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
2013 	}
2014 	if (et != AHCI_ERR_NONE)
2015 		ch->eslots |= (1 << slot->slot);
2016 	/* In case of error, freeze device for proper recovery. */
2017 	if ((et != AHCI_ERR_NONE) && (!ch->recoverycmd) &&
2018 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
2019 		xpt_freeze_devq(ccb->ccb_h.path, 1);
2020 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
2021 	}
2022 	/* Set proper result status. */
2023 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2024 	switch (et) {
2025 	case AHCI_ERR_NONE:
2026 		ccb->ccb_h.status |= CAM_REQ_CMP;
2027 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
2028 			ccb->csio.scsi_status = SCSI_STATUS_OK;
2029 		break;
2030 	case AHCI_ERR_INVALID:
2031 		ch->fatalerr = 1;
2032 		ccb->ccb_h.status |= CAM_REQ_INVALID;
2033 		break;
2034 	case AHCI_ERR_INNOCENT:
2035 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
2036 		break;
2037 	case AHCI_ERR_TFE:
2038 	case AHCI_ERR_NCQ:
2039 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2040 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
2041 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
2042 		} else {
2043 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
2044 		}
2045 		break;
2046 	case AHCI_ERR_SATA:
2047 		ch->fatalerr = 1;
2048 		if (!ch->recoverycmd) {
2049 			xpt_freeze_simq(ch->sim, 1);
2050 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2051 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2052 		}
2053 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
2054 		break;
2055 	case AHCI_ERR_TIMEOUT:
2056 		if (!ch->recoverycmd) {
2057 			xpt_freeze_simq(ch->sim, 1);
2058 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2059 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2060 		}
2061 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
2062 		break;
2063 	default:
2064 		ch->fatalerr = 1;
2065 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2066 	}
2067 	/* Free slot. */
2068 	ch->oslots &= ~(1 << slot->slot);
2069 	ch->rslots &= ~(1 << slot->slot);
2070 	ch->aslots &= ~(1 << slot->slot);
2071 	slot->state = AHCI_SLOT_EMPTY;
2072 	slot->ccb = NULL;
2073 	/* Update channel stats. */
2074 	ch->numrslots--;
2075 	ch->numrslotspd[ccb->ccb_h.target_id]--;
2076 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2077 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
2078 		ch->numtslots--;
2079 		ch->numtslotspd[ccb->ccb_h.target_id]--;
2080 	}
2081 	/* Cancel timeout state if request completed normally. */
2082 	if (et != AHCI_ERR_TIMEOUT) {
2083 		lastto = (ch->toslots == (1 << slot->slot));
2084 		ch->toslots &= ~(1 << slot->slot);
2085 		if (lastto)
2086 			xpt_release_simq(ch->sim, TRUE);
2087 	}
2088 	/* If it was first request of reset sequence and there is no error,
2089 	 * proceed to second request. */
2090 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
2091 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
2092 	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
2093 	    et == AHCI_ERR_NONE) {
2094 		ccb->ataio.cmd.control &= ~ATA_A_RESET;
2095 		ahci_begin_transaction(ch, ccb);
2096 		return;
2097 	}
2098 	/* If it was our READ LOG command - process it. */
2099 	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
2100 		ahci_process_read_log(ch, ccb);
2101 	/* If it was our REQUEST SENSE command - process it. */
2102 	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
2103 		ahci_process_request_sense(ch, ccb);
2104 	/* If it was NCQ or ATAPI command error, put result on hold. */
2105 	} else if (et == AHCI_ERR_NCQ ||
2106 	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
2107 	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
2108 		ch->hold[slot->slot] = ccb;
2109 		ch->numhslots++;
2110 	} else
2111 		ahci_done(ch, ccb);
2112 	/* If we have no other active commands, ... */
2113 	if (ch->rslots == 0) {
2114 		/* if there was fatal error - reset port. */
2115 		if (ch->toslots != 0 || ch->fatalerr) {
2116 			ahci_reset(ch);
2117 		} else {
2118 			/* if we have slots in error, we can reinit port. */
2119 			if (ch->eslots != 0) {
2120 				ahci_stop(ch);
2121 				ahci_clo(ch);
2122 				ahci_start(ch, 1);
2123 			}
2124 			/* if there commands on hold, we can do READ LOG. */
2125 			if (!ch->recoverycmd && ch->numhslots)
2126 				ahci_issue_recovery(ch);
2127 		}
2128 	/* If all the rest of commands are in timeout - give them chance. */
2129 	} else if ((ch->rslots & ~ch->toslots) == 0 &&
2130 	    et != AHCI_ERR_TIMEOUT)
2131 		ahci_rearm_timeout(ch);
2132 	/* Unfreeze frozen command. */
2133 	if (ch->frozen && !ahci_check_collision(ch, ch->frozen)) {
2134 		union ccb *fccb = ch->frozen;
2135 		ch->frozen = NULL;
2136 		ahci_begin_transaction(ch, fccb);
2137 		xpt_release_simq(ch->sim, TRUE);
2138 	}
2139 	/* Start PM timer. */
2140 	if (ch->numrslots == 0 && ch->pm_level > 3 &&
2141 	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
2142 		callout_schedule(&ch->pm_timer,
2143 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
2144 	}
2145 }
2146 
2147 static void
2148 ahci_issue_recovery(struct ahci_channel *ch)
2149 {
2150 	union ccb *ccb;
2151 	struct ccb_ataio *ataio;
2152 	struct ccb_scsiio *csio;
2153 	int i;
2154 
2155 	/* Find some held command. */
2156 	for (i = 0; i < ch->numslots; i++) {
2157 		if (ch->hold[i])
2158 			break;
2159 	}
2160 	ccb = xpt_alloc_ccb_nowait();
2161 	if (ccb == NULL) {
2162 		device_printf(ch->dev, "Unable to allocate recovery command\n");
2163 completeall:
2164 		/* We can't do anything -- complete held commands. */
2165 		for (i = 0; i < ch->numslots; i++) {
2166 			if (ch->hold[i] == NULL)
2167 				continue;
2168 			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2169 			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
2170 			ahci_done(ch, ch->hold[i]);
2171 			ch->hold[i] = NULL;
2172 			ch->numhslots--;
2173 		}
2174 		ahci_reset(ch);
2175 		return;
2176 	}
2177 	xpt_setup_ccb(&ccb->ccb_h, ch->hold[i]->ccb_h.path,
2178 	    ch->hold[i]->ccb_h.pinfo.priority);
2179 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2180 		/* READ LOG */
2181 		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
2182 		ccb->ccb_h.func_code = XPT_ATA_IO;
2183 		ccb->ccb_h.flags = CAM_DIR_IN;
2184 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2185 		ataio = &ccb->ataio;
2186 		ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
2187 		if (ataio->data_ptr == NULL) {
2188 			xpt_free_ccb(ccb);
2189 			device_printf(ch->dev,
2190 			    "Unable to allocate memory for READ LOG command\n");
2191 			goto completeall;
2192 		}
2193 		ataio->dxfer_len = 512;
2194 		bzero(&ataio->cmd, sizeof(ataio->cmd));
2195 		ataio->cmd.flags = CAM_ATAIO_48BIT;
2196 		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
2197 		ataio->cmd.sector_count = 1;
2198 		ataio->cmd.sector_count_exp = 0;
2199 		ataio->cmd.lba_low = 0x10;
2200 		ataio->cmd.lba_mid = 0;
2201 		ataio->cmd.lba_mid_exp = 0;
2202 	} else {
2203 		/* REQUEST SENSE */
2204 		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
2205 		ccb->ccb_h.recovery_slot = i;
2206 		ccb->ccb_h.func_code = XPT_SCSI_IO;
2207 		ccb->ccb_h.flags = CAM_DIR_IN;
2208 		ccb->ccb_h.status = 0;
2209 		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2210 		csio = &ccb->csio;
2211 		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
2212 		csio->dxfer_len = ch->hold[i]->csio.sense_len;
2213 		csio->cdb_len = 6;
2214 		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
2215 		csio->cdb_io.cdb_bytes[0] = 0x03;
2216 		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
2217 	}
2218 	/* Freeze SIM while doing recovery. */
2219 	ch->recoverycmd = 1;
2220 	xpt_freeze_simq(ch->sim, 1);
2221 	ahci_begin_transaction(ch, ccb);
2222 }
2223 
2224 static void
2225 ahci_process_read_log(struct ahci_channel *ch, union ccb *ccb)
2226 {
2227 	uint8_t *data;
2228 	struct ata_res *res;
2229 	int i;
2230 
2231 	ch->recoverycmd = 0;
2232 
2233 	data = ccb->ataio.data_ptr;
2234 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2235 	    (data[0] & 0x80) == 0) {
2236 		for (i = 0; i < ch->numslots; i++) {
2237 			if (!ch->hold[i])
2238 				continue;
2239 			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2240 				continue;
2241 			if ((data[0] & 0x1F) == i) {
2242 				res = &ch->hold[i]->ataio.res;
2243 				res->status = data[2];
2244 				res->error = data[3];
2245 				res->lba_low = data[4];
2246 				res->lba_mid = data[5];
2247 				res->lba_high = data[6];
2248 				res->device = data[7];
2249 				res->lba_low_exp = data[8];
2250 				res->lba_mid_exp = data[9];
2251 				res->lba_high_exp = data[10];
2252 				res->sector_count = data[12];
2253 				res->sector_count_exp = data[13];
2254 			} else {
2255 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2256 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2257 			}
2258 			ahci_done(ch, ch->hold[i]);
2259 			ch->hold[i] = NULL;
2260 			ch->numhslots--;
2261 		}
2262 	} else {
2263 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2264 			device_printf(ch->dev, "Error while READ LOG EXT\n");
2265 		else if ((data[0] & 0x80) == 0) {
2266 			device_printf(ch->dev, "Non-queued command error in READ LOG EXT\n");
2267 		}
2268 		for (i = 0; i < ch->numslots; i++) {
2269 			if (!ch->hold[i])
2270 				continue;
2271 			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2272 				continue;
2273 			ahci_done(ch, ch->hold[i]);
2274 			ch->hold[i] = NULL;
2275 			ch->numhslots--;
2276 		}
2277 	}
2278 	free(ccb->ataio.data_ptr, M_AHCI);
2279 	xpt_free_ccb(ccb);
2280 	xpt_release_simq(ch->sim, TRUE);
2281 }
2282 
2283 static void
2284 ahci_process_request_sense(struct ahci_channel *ch, union ccb *ccb)
2285 {
2286 	int i;
2287 
2288 	ch->recoverycmd = 0;
2289 
2290 	i = ccb->ccb_h.recovery_slot;
2291 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2292 		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
2293 	} else {
2294 		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2295 		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
2296 	}
2297 	ahci_done(ch, ch->hold[i]);
2298 	ch->hold[i] = NULL;
2299 	ch->numhslots--;
2300 	xpt_free_ccb(ccb);
2301 	xpt_release_simq(ch->sim, TRUE);
2302 }
2303 
2304 static void
2305 ahci_start(struct ahci_channel *ch, int fbs)
2306 {
2307 	u_int32_t cmd;
2308 
2309 	/* Run the channel start callback, if any. */
2310 	if (ch->start)
2311 		ch->start(ch);
2312 
2313 	/* Clear SATA error register */
2314 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2315 	/* Clear any interrupts pending on this channel */
2316 	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2317 	/* Configure FIS-based switching if supported. */
2318 	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2319 		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2320 		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2321 		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2322 	}
2323 	/* Start operations on this channel */
2324 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2325 	cmd &= ~AHCI_P_CMD_PMA;
2326 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2327 	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2328 }
2329 
2330 static void
2331 ahci_stop(struct ahci_channel *ch)
2332 {
2333 	u_int32_t cmd;
2334 	int timeout;
2335 
2336 	/* Kill all activity on this channel */
2337 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2338 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2339 	/* Wait for activity stop. */
2340 	timeout = 0;
2341 	do {
2342 		DELAY(10);
2343 		if (timeout++ > 50000) {
2344 			device_printf(ch->dev, "stopping AHCI engine failed\n");
2345 			break;
2346 		}
2347 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2348 	ch->eslots = 0;
2349 }
2350 
2351 static void
2352 ahci_clo(struct ahci_channel *ch)
2353 {
2354 	u_int32_t cmd;
2355 	int timeout;
2356 
2357 	/* Issue Command List Override if supported */
2358 	if (ch->caps & AHCI_CAP_SCLO) {
2359 		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2360 		cmd |= AHCI_P_CMD_CLO;
2361 		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2362 		timeout = 0;
2363 		do {
2364 			DELAY(10);
2365 			if (timeout++ > 50000) {
2366 			    device_printf(ch->dev, "executing CLO failed\n");
2367 			    break;
2368 			}
2369 		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2370 	}
2371 }
2372 
2373 static void
2374 ahci_stop_fr(struct ahci_channel *ch)
2375 {
2376 	u_int32_t cmd;
2377 	int timeout;
2378 
2379 	/* Kill all FIS reception on this channel */
2380 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2381 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2382 	/* Wait for FIS reception stop. */
2383 	timeout = 0;
2384 	do {
2385 		DELAY(10);
2386 		if (timeout++ > 50000) {
2387 			device_printf(ch->dev, "stopping AHCI FR engine failed\n");
2388 			break;
2389 		}
2390 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2391 }
2392 
2393 static void
2394 ahci_start_fr(struct ahci_channel *ch)
2395 {
2396 	u_int32_t cmd;
2397 
2398 	/* Start FIS reception on this channel */
2399 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2400 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2401 }
2402 
2403 static int
2404 ahci_wait_ready(struct ahci_channel *ch, int t, int t0)
2405 {
2406 	int timeout = 0;
2407 	uint32_t val;
2408 
2409 	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2410 	    (ATA_S_BUSY | ATA_S_DRQ)) {
2411 		if (timeout > t) {
2412 			if (t != 0) {
2413 				device_printf(ch->dev,
2414 				    "AHCI reset: device not ready after %dms "
2415 				    "(tfd = %08x)\n",
2416 				    MAX(t, 0) + t0, val);
2417 			}
2418 			return (EBUSY);
2419 		}
2420 		DELAY(1000);
2421 		timeout++;
2422 	}
2423 	if (bootverbose)
2424 		device_printf(ch->dev, "AHCI reset: device ready after %dms\n",
2425 		    timeout + t0);
2426 	return (0);
2427 }
2428 
2429 static void
2430 ahci_reset_to(void *arg)
2431 {
2432 	struct ahci_channel *ch = arg;
2433 
2434 	if (ch->resetting == 0)
2435 		return;
2436 	ch->resetting--;
2437 	if (ahci_wait_ready(ch, ch->resetting == 0 ? -1 : 0,
2438 	    (310 - ch->resetting) * 100) == 0) {
2439 		ch->resetting = 0;
2440 		ahci_start(ch, 1);
2441 		xpt_release_simq(ch->sim, TRUE);
2442 		return;
2443 	}
2444 	if (ch->resetting == 0) {
2445 		ahci_clo(ch);
2446 		ahci_start(ch, 1);
2447 		xpt_release_simq(ch->sim, TRUE);
2448 		return;
2449 	}
2450 	callout_schedule(&ch->reset_timer, hz / 10);
2451 }
2452 
2453 static void
2454 ahci_reset(struct ahci_channel *ch)
2455 {
2456 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(ch->dev));
2457 	int i;
2458 
2459 	xpt_freeze_simq(ch->sim, 1);
2460 	if (bootverbose)
2461 		device_printf(ch->dev, "AHCI reset...\n");
2462 	/* Forget about previous reset. */
2463 	if (ch->resetting) {
2464 		ch->resetting = 0;
2465 		callout_stop(&ch->reset_timer);
2466 		xpt_release_simq(ch->sim, TRUE);
2467 	}
2468 	/* Requeue freezed command. */
2469 	if (ch->frozen) {
2470 		union ccb *fccb = ch->frozen;
2471 		ch->frozen = NULL;
2472 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2473 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2474 			xpt_freeze_devq(fccb->ccb_h.path, 1);
2475 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2476 		}
2477 		ahci_done(ch, fccb);
2478 	}
2479 	/* Kill the engine and requeue all running commands. */
2480 	ahci_stop(ch);
2481 	for (i = 0; i < ch->numslots; i++) {
2482 		/* Do we have a running request on slot? */
2483 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2484 			continue;
2485 		/* XXX; Commands in loading state. */
2486 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2487 	}
2488 	for (i = 0; i < ch->numslots; i++) {
2489 		if (!ch->hold[i])
2490 			continue;
2491 		ahci_done(ch, ch->hold[i]);
2492 		ch->hold[i] = NULL;
2493 		ch->numhslots--;
2494 	}
2495 	if (ch->toslots != 0)
2496 		xpt_release_simq(ch->sim, TRUE);
2497 	ch->eslots = 0;
2498 	ch->toslots = 0;
2499 	ch->wrongccs = 0;
2500 	ch->fatalerr = 0;
2501 	/* Tell the XPT about the event */
2502 	xpt_async(AC_BUS_RESET, ch->path, NULL);
2503 	/* Disable port interrupts */
2504 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2505 	/* Reset and reconnect PHY, */
2506 	if (!ahci_sata_phy_reset(ch)) {
2507 		if (bootverbose)
2508 			device_printf(ch->dev,
2509 			    "AHCI reset: device not found\n");
2510 		ch->devices = 0;
2511 		/* Enable wanted port interrupts */
2512 		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2513 		    (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2514 		     AHCI_P_IX_PRC | AHCI_P_IX_PC));
2515 		xpt_release_simq(ch->sim, TRUE);
2516 		return;
2517 	}
2518 	if (bootverbose)
2519 		device_printf(ch->dev, "AHCI reset: device found\n");
2520 	/* Wait for clearing busy status. */
2521 	if (ahci_wait_ready(ch, dumping ? 31000 : 0, 0)) {
2522 		if (dumping)
2523 			ahci_clo(ch);
2524 		else
2525 			ch->resetting = 310;
2526 	}
2527 	ch->devices = 1;
2528 	/* Enable wanted port interrupts */
2529 	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2530 	     (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2531 	      AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2532 	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2533 	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC : 0) | AHCI_P_IX_PC |
2534 	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2535 	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2536 	if (ch->resetting)
2537 		callout_reset(&ch->reset_timer, hz / 10, ahci_reset_to, ch);
2538 	else {
2539 		ahci_start(ch, 1);
2540 		xpt_release_simq(ch->sim, TRUE);
2541 	}
2542 }
2543 
2544 static int
2545 ahci_setup_fis(struct ahci_channel *ch, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2546 {
2547 	u_int8_t *fis = &ctp->cfis[0];
2548 
2549 	bzero(fis, 20);
2550 	fis[0] = 0x27;  		/* host to device */
2551 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2552 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2553 		fis[1] |= 0x80;
2554 		fis[2] = ATA_PACKET_CMD;
2555 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2556 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2557 			fis[3] = ATA_F_DMA;
2558 		else {
2559 			fis[5] = ccb->csio.dxfer_len;
2560 		        fis[6] = ccb->csio.dxfer_len >> 8;
2561 		}
2562 		fis[7] = ATA_D_LBA;
2563 		fis[15] = ATA_A_4BIT;
2564 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2565 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2566 		    ctp->acmd, ccb->csio.cdb_len);
2567 		bzero(ctp->acmd + ccb->csio.cdb_len, 32 - ccb->csio.cdb_len);
2568 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2569 		fis[1] |= 0x80;
2570 		fis[2] = ccb->ataio.cmd.command;
2571 		fis[3] = ccb->ataio.cmd.features;
2572 		fis[4] = ccb->ataio.cmd.lba_low;
2573 		fis[5] = ccb->ataio.cmd.lba_mid;
2574 		fis[6] = ccb->ataio.cmd.lba_high;
2575 		fis[7] = ccb->ataio.cmd.device;
2576 		fis[8] = ccb->ataio.cmd.lba_low_exp;
2577 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2578 		fis[10] = ccb->ataio.cmd.lba_high_exp;
2579 		fis[11] = ccb->ataio.cmd.features_exp;
2580 		fis[12] = ccb->ataio.cmd.sector_count;
2581 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2582 			fis[12] &= 0x07;
2583 			fis[12] |= tag << 3;
2584 		}
2585 		fis[13] = ccb->ataio.cmd.sector_count_exp;
2586 		if (ccb->ataio.ata_flags & ATA_FLAG_ICC)
2587 			fis[14] = ccb->ataio.icc;
2588 		fis[15] = ATA_A_4BIT;
2589 		if (ccb->ataio.ata_flags & ATA_FLAG_AUX) {
2590 			fis[16] =  ccb->ataio.aux        & 0xff;
2591 			fis[17] = (ccb->ataio.aux >>  8) & 0xff;
2592 			fis[18] = (ccb->ataio.aux >> 16) & 0xff;
2593 			fis[19] = (ccb->ataio.aux >> 24) & 0xff;
2594 		}
2595 	} else {
2596 		fis[15] = ccb->ataio.cmd.control;
2597 	}
2598 	return (20);
2599 }
2600 
2601 static int
2602 ahci_sata_connect(struct ahci_channel *ch)
2603 {
2604 	u_int32_t status;
2605 	int timeout, timeoutslot, found = 0;
2606 
2607 	/*
2608 	 * Wait for "connect well", up to 100ms by default and
2609 	 * up to 500ms for devices with the SLOWDEV quirk.
2610 	 */
2611 	timeoutslot = ((ch->quirks & AHCI_Q_SLOWDEV) ? 5000 : 1000);
2612 	for (timeout = 0; timeout < timeoutslot; timeout++) {
2613 		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2614 		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
2615 			found = 1;
2616 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2617 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2618 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2619 			break;
2620 		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2621 			if (bootverbose) {
2622 				device_printf(ch->dev, "SATA offline status=%08x\n",
2623 				    status);
2624 			}
2625 			return (0);
2626 		}
2627 		if (found == 0 && timeout >= 100)
2628 			break;
2629 		DELAY(100);
2630 	}
2631 	if (timeout >= timeoutslot || !found) {
2632 		if (bootverbose) {
2633 			device_printf(ch->dev,
2634 			    "SATA connect timeout time=%dus status=%08x\n",
2635 			    timeout * 100, status);
2636 		}
2637 		return (0);
2638 	}
2639 	if (bootverbose) {
2640 		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2641 		    timeout * 100, status);
2642 	}
2643 	/* Clear SATA error register */
2644 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2645 	return (1);
2646 }
2647 
2648 static int
2649 ahci_sata_phy_reset(struct ahci_channel *ch)
2650 {
2651 	int sata_rev;
2652 	uint32_t val, detval;
2653 
2654 	if (ch->listening) {
2655 		val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2656 		val |= AHCI_P_CMD_SUD;
2657 		ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2658 		ch->listening = 0;
2659 	}
2660 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2661 	if (sata_rev == 1)
2662 		val = ATA_SC_SPD_SPEED_GEN1;
2663 	else if (sata_rev == 2)
2664 		val = ATA_SC_SPD_SPEED_GEN2;
2665 	else if (sata_rev == 3)
2666 		val = ATA_SC_SPD_SPEED_GEN3;
2667 	else
2668 		val = 0;
2669 	detval = ahci_ch_detval(ch, ATA_SC_DET_RESET);
2670 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2671 	    detval | val |
2672 	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2673 	DELAY(1000);
2674 	detval = ahci_ch_detval(ch, ATA_SC_DET_IDLE);
2675 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2676 	    detval | val | ((ch->pm_level > 0) ? 0 :
2677 	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2678 	if (!ahci_sata_connect(ch)) {
2679 		if (ch->caps & AHCI_CAP_SSS) {
2680 			val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2681 			val &= ~AHCI_P_CMD_SUD;
2682 			ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2683 			ch->listening = 1;
2684 		} else if (ch->pm_level > 0)
2685 			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2686 		return (0);
2687 	}
2688 	return (1);
2689 }
2690 
2691 static int
2692 ahci_check_ids(struct ahci_channel *ch, union ccb *ccb)
2693 {
2694 
2695 	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2696 		ccb->ccb_h.status = CAM_TID_INVALID;
2697 		ahci_done(ch, ccb);
2698 		return (-1);
2699 	}
2700 	if (ccb->ccb_h.target_lun != 0) {
2701 		ccb->ccb_h.status = CAM_LUN_INVALID;
2702 		ahci_done(ch, ccb);
2703 		return (-1);
2704 	}
2705 	return (0);
2706 }
2707 
2708 static void
2709 ahciaction(struct cam_sim *sim, union ccb *ccb)
2710 {
2711 	struct ahci_channel *ch;
2712 
2713 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2714 	    ccb->ccb_h.func_code));
2715 
2716 	ch = (struct ahci_channel *)cam_sim_softc(sim);
2717 	switch (ccb->ccb_h.func_code) {
2718 	/* Common cases first */
2719 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2720 	case XPT_SCSI_IO:
2721 		if (ahci_check_ids(ch, ccb))
2722 			return;
2723 		if (ch->devices == 0 ||
2724 		    (ch->pm_present == 0 &&
2725 		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2726 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2727 			break;
2728 		}
2729 		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2730 		/* Check for command collision. */
2731 		if (ahci_check_collision(ch, ccb)) {
2732 			/* Freeze command. */
2733 			ch->frozen = ccb;
2734 			/* We have only one frozen slot, so freeze simq also. */
2735 			xpt_freeze_simq(ch->sim, 1);
2736 			return;
2737 		}
2738 		ahci_begin_transaction(ch, ccb);
2739 		return;
2740 	case XPT_ABORT:			/* Abort the specified CCB */
2741 		/* XXX Implement */
2742 		ccb->ccb_h.status = CAM_REQ_INVALID;
2743 		break;
2744 	case XPT_SET_TRAN_SETTINGS:
2745 	{
2746 		struct	ccb_trans_settings *cts = &ccb->cts;
2747 		struct	ahci_device *d;
2748 
2749 		if (ahci_check_ids(ch, ccb))
2750 			return;
2751 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2752 			d = &ch->curr[ccb->ccb_h.target_id];
2753 		else
2754 			d = &ch->user[ccb->ccb_h.target_id];
2755 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2756 			d->revision = cts->xport_specific.sata.revision;
2757 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2758 			d->mode = cts->xport_specific.sata.mode;
2759 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2760 			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2761 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2762 			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2763 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2764 			ch->pm_present = cts->xport_specific.sata.pm_present;
2765 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2766 			d->atapi = cts->xport_specific.sata.atapi;
2767 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2768 			d->caps = cts->xport_specific.sata.caps;
2769 		ccb->ccb_h.status = CAM_REQ_CMP;
2770 		break;
2771 	}
2772 	case XPT_GET_TRAN_SETTINGS:
2773 	/* Get default/user set transfer settings for the target */
2774 	{
2775 		struct	ccb_trans_settings *cts = &ccb->cts;
2776 		struct  ahci_device *d;
2777 		uint32_t status;
2778 
2779 		if (ahci_check_ids(ch, ccb))
2780 			return;
2781 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2782 			d = &ch->curr[ccb->ccb_h.target_id];
2783 		else
2784 			d = &ch->user[ccb->ccb_h.target_id];
2785 		cts->protocol = PROTO_UNSPECIFIED;
2786 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2787 		cts->transport = XPORT_SATA;
2788 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2789 		cts->proto_specific.valid = 0;
2790 		cts->xport_specific.sata.valid = 0;
2791 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2792 		    (ccb->ccb_h.target_id == 15 ||
2793 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2794 			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2795 			if (status & 0x0f0) {
2796 				cts->xport_specific.sata.revision =
2797 				    (status & 0x0f0) >> 4;
2798 				cts->xport_specific.sata.valid |=
2799 				    CTS_SATA_VALID_REVISION;
2800 			}
2801 			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2802 			if (ch->pm_level) {
2803 				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2804 					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2805 				if (ch->caps2 & AHCI_CAP2_APST)
2806 					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2807 			}
2808 			if ((ch->caps & AHCI_CAP_SNCQ) &&
2809 			    (ch->quirks & AHCI_Q_NOAA) == 0)
2810 				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2811 			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2812 			cts->xport_specific.sata.caps &=
2813 			    ch->user[ccb->ccb_h.target_id].caps;
2814 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2815 		} else {
2816 			cts->xport_specific.sata.revision = d->revision;
2817 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2818 			cts->xport_specific.sata.caps = d->caps;
2819 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2820 		}
2821 		cts->xport_specific.sata.mode = d->mode;
2822 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2823 		cts->xport_specific.sata.bytecount = d->bytecount;
2824 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2825 		cts->xport_specific.sata.pm_present = ch->pm_present;
2826 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2827 		cts->xport_specific.sata.tags = d->tags;
2828 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2829 		cts->xport_specific.sata.atapi = d->atapi;
2830 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2831 		ccb->ccb_h.status = CAM_REQ_CMP;
2832 		break;
2833 	}
2834 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2835 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2836 		ahci_reset(ch);
2837 		ccb->ccb_h.status = CAM_REQ_CMP;
2838 		break;
2839 	case XPT_TERM_IO:		/* Terminate the I/O process */
2840 		/* XXX Implement */
2841 		ccb->ccb_h.status = CAM_REQ_INVALID;
2842 		break;
2843 	case XPT_PATH_INQ:		/* Path routing inquiry */
2844 	{
2845 		struct ccb_pathinq *cpi = &ccb->cpi;
2846 
2847 		cpi->version_num = 1; /* XXX??? */
2848 		cpi->hba_inquiry = PI_SDTR_ABLE;
2849 		if (ch->caps & AHCI_CAP_SNCQ)
2850 			cpi->hba_inquiry |= PI_TAG_ABLE;
2851 		if (ch->caps & AHCI_CAP_SPM)
2852 			cpi->hba_inquiry |= PI_SATAPM;
2853 		cpi->target_sprt = 0;
2854 		cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED;
2855 		if ((ch->quirks & AHCI_Q_NOAUX) == 0)
2856 			cpi->hba_misc |= PIM_ATA_EXT;
2857 		cpi->hba_eng_cnt = 0;
2858 		if (ch->caps & AHCI_CAP_SPM)
2859 			cpi->max_target = 15;
2860 		else
2861 			cpi->max_target = 0;
2862 		cpi->max_lun = 0;
2863 		cpi->initiator_id = 0;
2864 		cpi->bus_id = cam_sim_bus(sim);
2865 		cpi->base_transfer_speed = 150000;
2866 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2867 		strlcpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2868 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2869 		cpi->unit_number = cam_sim_unit(sim);
2870 		cpi->transport = XPORT_SATA;
2871 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2872 		cpi->protocol = PROTO_ATA;
2873 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2874 		cpi->maxio = ctob(AHCI_SG_ENTRIES - 1);
2875 		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2876 		if (ch->quirks & AHCI_Q_MAXIO_64K)
2877 			cpi->maxio = min(cpi->maxio, 128 * 512);
2878 		cpi->hba_vendor = ch->vendorid;
2879 		cpi->hba_device = ch->deviceid;
2880 		cpi->hba_subvendor = ch->subvendorid;
2881 		cpi->hba_subdevice = ch->subdeviceid;
2882 		cpi->ccb_h.status = CAM_REQ_CMP;
2883 		break;
2884 	}
2885 	default:
2886 		ccb->ccb_h.status = CAM_REQ_INVALID;
2887 		break;
2888 	}
2889 	ahci_done(ch, ccb);
2890 }
2891 
2892 static void
2893 ahcipoll(struct cam_sim *sim)
2894 {
2895 	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2896 	uint32_t istatus;
2897 
2898 	/* Read interrupt statuses and process if any. */
2899 	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
2900 	if (istatus != 0)
2901 		ahci_ch_intr_main(ch, istatus);
2902 	if (ch->resetting != 0 &&
2903 	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2904 		ch->resetpolldiv = 1000;
2905 		ahci_reset_to(ch);
2906 	}
2907 }
2908 
2909 MODULE_VERSION(ahci, 1);
2910 MODULE_DEPEND(ahci, cam, 1, 1, 1);
2911