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