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