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