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