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