xref: /freebsd/sys/dev/ahci/ahci.c (revision dcc3a33188bceb5b6e819efdb9c5f72d059084b6)
1 /*-
2  * Copyright (c) 2009 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/ata.h>
35 #include <sys/bus.h>
36 #include <sys/endian.h>
37 #include <sys/malloc.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/sema.h>
41 #include <sys/taskqueue.h>
42 #include <vm/uma.h>
43 #include <machine/stdarg.h>
44 #include <machine/resource.h>
45 #include <machine/bus.h>
46 #include <sys/rman.h>
47 #include <dev/pci/pcivar.h>
48 #include <dev/pci/pcireg.h>
49 #include "ahci.h"
50 
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_sim.h>
54 #include <cam/cam_xpt_sim.h>
55 #include <cam/cam_xpt_periph.h>
56 #include <cam/cam_debug.h>
57 
58 /* local prototypes */
59 static int ahci_setup_interrupt(device_t dev);
60 static void ahci_intr(void *data);
61 static void ahci_intr_one(void *data);
62 static int ahci_suspend(device_t dev);
63 static int ahci_resume(device_t dev);
64 static int ahci_ch_suspend(device_t dev);
65 static int ahci_ch_resume(device_t dev);
66 static void ahci_ch_pm(void *arg);
67 static void ahci_ch_intr_locked(void *data);
68 static void ahci_ch_intr(void *data);
69 static int ahci_ctlr_reset(device_t dev);
70 static void ahci_begin_transaction(device_t dev, union ccb *ccb);
71 static void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
72 static void ahci_execute_transaction(struct ahci_slot *slot);
73 static void ahci_timeout(struct ahci_slot *slot);
74 static void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
75 static int ahci_setup_fis(struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
76 static void ahci_dmainit(device_t dev);
77 static void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
78 static void ahci_dmafini(device_t dev);
79 static void ahci_slotsalloc(device_t dev);
80 static void ahci_slotsfree(device_t dev);
81 static void ahci_reset(device_t dev);
82 static void ahci_start(device_t dev);
83 static void ahci_stop(device_t dev);
84 static void ahci_clo(device_t dev);
85 static void ahci_start_fr(device_t dev);
86 static void ahci_stop_fr(device_t dev);
87 
88 static int ahci_sata_connect(struct ahci_channel *ch);
89 static int ahci_sata_phy_reset(device_t dev, int quick);
90 
91 static void ahci_issue_read_log(device_t dev);
92 static void ahci_process_read_log(device_t dev, union ccb *ccb);
93 
94 static void ahciaction(struct cam_sim *sim, union ccb *ccb);
95 static void ahcipoll(struct cam_sim *sim);
96 
97 MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
98 
99 /*
100  * AHCI v1.x compliant SATA chipset support functions
101  */
102 static int
103 ahci_probe(device_t dev)
104 {
105 
106 	/* is this a possible AHCI candidate ? */
107 	if (pci_get_class(dev) != PCIC_STORAGE ||
108 	    pci_get_subclass(dev) != PCIS_STORAGE_SATA)
109 		return (ENXIO);
110 
111 	/* is this PCI device flagged as an AHCI compliant chip ? */
112 	if (pci_get_progif(dev) != PCIP_STORAGE_SATA_AHCI_1_0)
113 		return (ENXIO);
114 
115 	device_set_desc_copy(dev, "AHCI controller");
116 	return (BUS_PROBE_VENDOR);
117 }
118 
119 static int
120 ahci_attach(device_t dev)
121 {
122 	struct ahci_controller *ctlr = device_get_softc(dev);
123 	device_t child;
124 	int	error, unit, speed;
125 	u_int32_t version;
126 
127 	ctlr->dev = dev;
128 	resource_int_value(device_get_name(dev),
129 	    device_get_unit(dev), "ccc", &ctlr->ccc);
130 	/* if we have a memory BAR(5) we are likely on an AHCI part */
131 	ctlr->r_rid = PCIR_BAR(5);
132 	if (!(ctlr->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
133 	    &ctlr->r_rid, RF_ACTIVE)))
134 		return ENXIO;
135 	/* Setup our own memory management for channels. */
136 	ctlr->sc_iomem.rm_type = RMAN_ARRAY;
137 	ctlr->sc_iomem.rm_descr = "I/O memory addresses";
138 	if ((error = rman_init(&ctlr->sc_iomem)) != 0) {
139 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
140 		return (error);
141 	}
142 	if ((error = rman_manage_region(&ctlr->sc_iomem,
143 	    rman_get_start(ctlr->r_mem), rman_get_end(ctlr->r_mem))) != 0) {
144 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
145 		rman_fini(&ctlr->sc_iomem);
146 		return (error);
147 	}
148 	/* Reset controller */
149 	if ((error = ahci_ctlr_reset(dev)) != 0) {
150 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
151 		rman_fini(&ctlr->sc_iomem);
152 		return (error);
153 	};
154 	/* Get the number of HW channels */
155 	ctlr->ichannels = ATA_INL(ctlr->r_mem, AHCI_PI);
156 	ctlr->channels = MAX(flsl(ctlr->ichannels),
157 	    (ATA_INL(ctlr->r_mem, AHCI_CAP) & AHCI_CAP_NPMASK) + 1);
158 	/* Setup interrupts. */
159 	if (ahci_setup_interrupt(dev)) {
160 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
161 		rman_fini(&ctlr->sc_iomem);
162 		return ENXIO;
163 	}
164 	/* Announce HW capabilities. */
165 	version = ATA_INL(ctlr->r_mem, AHCI_VS);
166 	ctlr->caps = ATA_INL(ctlr->r_mem, AHCI_CAP);
167 	if (version >= 0x00010020)
168 		ctlr->caps2 = ATA_INL(ctlr->r_mem, AHCI_CAP2);
169 	speed = (ctlr->caps & AHCI_CAP_ISS) >> AHCI_CAP_ISS_SHIFT;
170 	device_printf(dev,
171 		    "AHCI v%x.%02x with %d %sGbps ports, Port Multiplier %s\n",
172 		    ((version >> 20) & 0xf0) + ((version >> 16) & 0x0f),
173 		    ((version >> 4) & 0xf0) + (version & 0x0f),
174 		    (ctlr->caps & AHCI_CAP_NPMASK) + 1,
175 		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
176 		    ((speed == 3) ? "6":"?"))),
177 		    (ctlr->caps & AHCI_CAP_SPM) ?
178 		    "supported" : "not supported");
179 	if (bootverbose) {
180 		device_printf(dev, "Caps:%s%s%s%s%s%s%s%s %sGbps",
181 		    (ctlr->caps & AHCI_CAP_64BIT) ? " 64bit":"",
182 		    (ctlr->caps & AHCI_CAP_SNCQ) ? " NCQ":"",
183 		    (ctlr->caps & AHCI_CAP_SSNTF) ? " SNTF":"",
184 		    (ctlr->caps & AHCI_CAP_SMPS) ? " MPS":"",
185 		    (ctlr->caps & AHCI_CAP_SSS) ? " SS":"",
186 		    (ctlr->caps & AHCI_CAP_SALP) ? " ALP":"",
187 		    (ctlr->caps & AHCI_CAP_SAL) ? " AL":"",
188 		    (ctlr->caps & AHCI_CAP_SCLO) ? " CLO":"",
189 		    ((speed == 1) ? "1.5":((speed == 2) ? "3":
190 		    ((speed == 3) ? "6":"?"))));
191 		printf("%s%s%s%s%s%s %dcmd%s%s%s %dports\n",
192 		    (ctlr->caps & AHCI_CAP_SAM) ? " AM":"",
193 		    (ctlr->caps & AHCI_CAP_SPM) ? " PM":"",
194 		    (ctlr->caps & AHCI_CAP_FBSS) ? " FBS":"",
195 		    (ctlr->caps & AHCI_CAP_PMD) ? " PMD":"",
196 		    (ctlr->caps & AHCI_CAP_SSC) ? " SSC":"",
197 		    (ctlr->caps & AHCI_CAP_PSC) ? " PSC":"",
198 		    ((ctlr->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
199 		    (ctlr->caps & AHCI_CAP_CCCS) ? " CCC":"",
200 		    (ctlr->caps & AHCI_CAP_EMS) ? " EM":"",
201 		    (ctlr->caps & AHCI_CAP_SXS) ? " eSATA":"",
202 		    (ctlr->caps & AHCI_CAP_NPMASK) + 1);
203 	}
204 	if (bootverbose && version >= 0x00010020) {
205 		device_printf(dev, "Caps2:%s%s%s\n",
206 		    (ctlr->caps2 & AHCI_CAP2_APST) ? " APST":"",
207 		    (ctlr->caps2 & AHCI_CAP2_NVMP) ? " NVMP":"",
208 		    (ctlr->caps2 & AHCI_CAP2_BOH) ? " BOH":"");
209 	}
210 	/* Attach all channels on this controller */
211 	for (unit = 0; unit < ctlr->channels; unit++) {
212 		if ((ctlr->ichannels & (1 << unit)) == 0)
213 			continue;
214 		child = device_add_child(dev, "ahcich", -1);
215 		if (child == NULL)
216 			device_printf(dev, "failed to add channel device\n");
217 		else
218 			device_set_ivars(child, (void *)(intptr_t)unit);
219 	}
220 	bus_generic_attach(dev);
221 	return 0;
222 }
223 
224 static int
225 ahci_detach(device_t dev)
226 {
227 	struct ahci_controller *ctlr = device_get_softc(dev);
228 	device_t *children;
229 	int nchildren, i;
230 
231 	/* Detach & delete all children */
232 	if (!device_get_children(dev, &children, &nchildren)) {
233 		for (i = 0; i < nchildren; i++)
234 			device_delete_child(dev, children[i]);
235 		free(children, M_TEMP);
236 	}
237 	/* Free interrupts. */
238 	for (i = 0; i < ctlr->numirqs; i++) {
239 		if (ctlr->irqs[i].r_irq) {
240 			bus_teardown_intr(dev, ctlr->irqs[i].r_irq,
241 			    ctlr->irqs[i].handle);
242 			bus_release_resource(dev, SYS_RES_IRQ,
243 			    ctlr->irqs[i].r_irq_rid, ctlr->irqs[i].r_irq);
244 		}
245 	}
246 	pci_release_msi(dev);
247 	/* Free memory. */
248 	rman_fini(&ctlr->sc_iomem);
249 	if (ctlr->r_mem)
250 		bus_release_resource(dev, SYS_RES_MEMORY, ctlr->r_rid, ctlr->r_mem);
251 	return (0);
252 }
253 
254 static int
255 ahci_ctlr_reset(device_t dev)
256 {
257 	struct ahci_controller *ctlr = device_get_softc(dev);
258 	int timeout;
259 
260 	if (pci_read_config(dev, 0x00, 4) == 0x28298086 &&
261 	    (pci_read_config(dev, 0x92, 1) & 0xfe) == 0x04)
262 		pci_write_config(dev, 0x92, 0x01, 1);
263 	/* Enable AHCI mode */
264 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
265 	/* Reset AHCI controller */
266 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE|AHCI_GHC_HR);
267 	for (timeout = 1000; timeout > 0; timeout--) {
268 		DELAY(1000);
269 		if ((ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_HR) == 0)
270 			break;
271 	}
272 	if (timeout == 0) {
273 		device_printf(dev, "AHCI controller reset failure\n");
274 		return ENXIO;
275 	}
276 	/* Reenable AHCI mode */
277 	ATA_OUTL(ctlr->r_mem, AHCI_GHC, AHCI_GHC_AE);
278 	/* Clear interrupts */
279 	ATA_OUTL(ctlr->r_mem, AHCI_IS, ATA_INL(ctlr->r_mem, AHCI_IS));
280 	/* Configure CCC */
281 	if (ctlr->ccc) {
282 		ATA_OUTL(ctlr->r_mem, AHCI_CCCP, ATA_INL(ctlr->r_mem, AHCI_PI));
283 		ATA_OUTL(ctlr->r_mem, AHCI_CCCC,
284 		    (ctlr->ccc << AHCI_CCCC_TV_SHIFT) |
285 		    (4 << AHCI_CCCC_CC_SHIFT) |
286 		    AHCI_CCCC_EN);
287 		ctlr->cccv = (ATA_INL(ctlr->r_mem, AHCI_CCCC) &
288 		    AHCI_CCCC_INT_MASK) >> AHCI_CCCC_INT_SHIFT;
289 		if (bootverbose) {
290 			device_printf(dev,
291 			    "CCC with %dms/4cmd enabled on vector %d\n",
292 			    ctlr->ccc, ctlr->cccv);
293 		}
294 	}
295 	/* Enable AHCI interrupts */
296 	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
297 	    ATA_INL(ctlr->r_mem, AHCI_GHC) | AHCI_GHC_IE);
298 	return (0);
299 }
300 
301 static int
302 ahci_suspend(device_t dev)
303 {
304 	struct ahci_controller *ctlr = device_get_softc(dev);
305 
306 	bus_generic_suspend(dev);
307 	/* Disable interupts, so the state change(s) doesn't trigger */
308 	ATA_OUTL(ctlr->r_mem, AHCI_GHC,
309 	     ATA_INL(ctlr->r_mem, AHCI_GHC) & (~AHCI_GHC_IE));
310 	return 0;
311 }
312 
313 static int
314 ahci_resume(device_t dev)
315 {
316 	int res;
317 
318 	if ((res = ahci_ctlr_reset(dev)) != 0)
319 		return (res);
320 	return (bus_generic_resume(dev));
321 }
322 
323 static int
324 ahci_setup_interrupt(device_t dev)
325 {
326 	struct ahci_controller *ctlr = device_get_softc(dev);
327 	int i, msi = 1;
328 
329 	/* Process hints. */
330 	resource_int_value(device_get_name(dev),
331 	    device_get_unit(dev), "msi", &msi);
332 	if (msi < 0)
333 		msi = 0;
334 	else if (msi == 1)
335 		msi = min(1, pci_msi_count(dev));
336 	else if (msi > 1)
337 		msi = pci_msi_count(dev);
338 	/* Allocate MSI if needed/present. */
339 	if (msi && pci_alloc_msi(dev, &msi) == 0) {
340 		ctlr->numirqs = msi;
341 	} else {
342 		msi = 0;
343 		ctlr->numirqs = 1;
344 	}
345 	/* Check for single MSI vector fallback. */
346 	if (ctlr->numirqs > 1 &&
347 	    (ATA_INL(ctlr->r_mem, AHCI_GHC) & AHCI_GHC_MRSM) != 0) {
348 		device_printf(dev, "Falling back to one MSI\n");
349 		ctlr->numirqs = 1;
350 	}
351 	/* Allocate all IRQs. */
352 	for (i = 0; i < ctlr->numirqs; i++) {
353 		ctlr->irqs[i].ctlr = ctlr;
354 		ctlr->irqs[i].r_irq_rid = i + (msi ? 1 : 0);
355 		if (ctlr->numirqs == 1 || i >= ctlr->channels ||
356 		    (ctlr->ccc && i == ctlr->cccv))
357 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ALL;
358 		else if (i == ctlr->numirqs - 1)
359 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_AFTER;
360 		else
361 			ctlr->irqs[i].mode = AHCI_IRQ_MODE_ONE;
362 		if (!(ctlr->irqs[i].r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
363 		    &ctlr->irqs[i].r_irq_rid, RF_SHAREABLE | RF_ACTIVE))) {
364 			device_printf(dev, "unable to map interrupt\n");
365 			return ENXIO;
366 		}
367 		if ((bus_setup_intr(dev, ctlr->irqs[i].r_irq, ATA_INTR_FLAGS, NULL,
368 		    (ctlr->irqs[i].mode == AHCI_IRQ_MODE_ONE) ? ahci_intr_one : ahci_intr,
369 		    &ctlr->irqs[i], &ctlr->irqs[i].handle))) {
370 			/* SOS XXX release r_irq */
371 			device_printf(dev, "unable to setup interrupt\n");
372 			return ENXIO;
373 		}
374 	}
375 	return (0);
376 }
377 
378 /*
379  * Common case interrupt handler.
380  */
381 static void
382 ahci_intr(void *data)
383 {
384 	struct ahci_controller_irq *irq = data;
385 	struct ahci_controller *ctlr = irq->ctlr;
386 	u_int32_t is;
387 	void *arg;
388 	int unit;
389 
390 	if (irq->mode == AHCI_IRQ_MODE_ALL) {
391 		unit = 0;
392 		if (ctlr->ccc)
393 			is = ctlr->ichannels;
394 		else
395 			is = ATA_INL(ctlr->r_mem, AHCI_IS);
396 	} else {	/* AHCI_IRQ_MODE_AFTER */
397 		unit = irq->r_irq_rid - 1;
398 		is = ATA_INL(ctlr->r_mem, AHCI_IS);
399 	}
400 	for (; unit < ctlr->channels; unit++) {
401 		if ((is & (1 << unit)) != 0 &&
402 		    (arg = ctlr->interrupt[unit].argument)) {
403 			ctlr->interrupt[unit].function(arg);
404 			ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
405 		}
406 	}
407 }
408 
409 /*
410  * Simplified interrupt handler for multivector MSI mode.
411  */
412 static void
413 ahci_intr_one(void *data)
414 {
415 	struct ahci_controller_irq *irq = data;
416 	struct ahci_controller *ctlr = irq->ctlr;
417 	void *arg;
418 	int unit;
419 
420 	unit = irq->r_irq_rid - 1;
421 	if ((arg = ctlr->interrupt[unit].argument))
422 	    ctlr->interrupt[unit].function(arg);
423 }
424 
425 static struct resource *
426 ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
427 		       u_long start, u_long end, u_long count, u_int flags)
428 {
429 	struct ahci_controller *ctlr = device_get_softc(dev);
430 	int unit = ((struct ahci_channel *)device_get_softc(child))->unit;
431 	struct resource *res = NULL;
432 	int offset = AHCI_OFFSET + (unit << 7);
433 	long st;
434 
435 	switch (type) {
436 	case SYS_RES_MEMORY:
437 		st = rman_get_start(ctlr->r_mem);
438 		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
439 		    st + offset + 127, 128, RF_ACTIVE, child);
440 		if (res) {
441 			bus_space_handle_t bsh;
442 			bus_space_tag_t bst;
443 			bsh = rman_get_bushandle(ctlr->r_mem);
444 			bst = rman_get_bustag(ctlr->r_mem);
445 			bus_space_subregion(bst, bsh, offset, 128, &bsh);
446 			rman_set_bushandle(res, bsh);
447 			rman_set_bustag(res, bst);
448 		}
449 		break;
450 	case SYS_RES_IRQ:
451 		if (*rid == ATA_IRQ_RID)
452 			res = ctlr->irqs[0].r_irq;
453 		break;
454 	}
455 	return (res);
456 }
457 
458 static int
459 ahci_release_resource(device_t dev, device_t child, int type, int rid,
460 			 struct resource *r)
461 {
462 
463 	switch (type) {
464 	case SYS_RES_MEMORY:
465 		rman_release_resource(r);
466 		return (0);
467 	case SYS_RES_IRQ:
468 		if (rid != ATA_IRQ_RID)
469 			return ENOENT;
470 		return (0);
471 	}
472 	return (EINVAL);
473 }
474 
475 static int
476 ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
477 		   int flags, driver_filter_t *filter, driver_intr_t *function,
478 		   void *argument, void **cookiep)
479 {
480 	struct ahci_controller *ctlr = device_get_softc(dev);
481 	int unit = (intptr_t)device_get_ivars(child);
482 
483 	if (filter != NULL) {
484 		printf("ahci.c: we cannot use a filter here\n");
485 		return (EINVAL);
486 	}
487 	ctlr->interrupt[unit].function = function;
488 	ctlr->interrupt[unit].argument = argument;
489 	return (0);
490 }
491 
492 static int
493 ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
494 		      void *cookie)
495 {
496 	struct ahci_controller *ctlr = device_get_softc(dev);
497 	int unit = (intptr_t)device_get_ivars(child);
498 
499 	ctlr->interrupt[unit].function = NULL;
500 	ctlr->interrupt[unit].argument = NULL;
501 	return (0);
502 }
503 
504 static int
505 ahci_print_child(device_t dev, device_t child)
506 {
507 	int retval;
508 
509 	retval = bus_print_child_header(dev, child);
510 	retval += printf(" at channel %d",
511 	    (int)(intptr_t)device_get_ivars(child));
512 	retval += bus_print_child_footer(dev, child);
513 
514 	return (retval);
515 }
516 
517 devclass_t ahci_devclass;
518 static device_method_t ahci_methods[] = {
519 	DEVMETHOD(device_probe,     ahci_probe),
520 	DEVMETHOD(device_attach,    ahci_attach),
521 	DEVMETHOD(device_detach,    ahci_detach),
522 	DEVMETHOD(device_suspend,   ahci_suspend),
523 	DEVMETHOD(device_resume,    ahci_resume),
524 	DEVMETHOD(bus_print_child,  ahci_print_child),
525 	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
526 	DEVMETHOD(bus_release_resource,     ahci_release_resource),
527 	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
528 	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
529 	{ 0, 0 }
530 };
531 static driver_t ahci_driver = {
532         "ahci",
533         ahci_methods,
534         sizeof(struct ahci_controller)
535 };
536 DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
537 MODULE_VERSION(ahci, 1);
538 MODULE_DEPEND(ahci, cam, 1, 1, 1);
539 
540 static int
541 ahci_ch_probe(device_t dev)
542 {
543 
544 	device_set_desc_copy(dev, "AHCI channel");
545 	return (0);
546 }
547 
548 static int
549 ahci_ch_attach(device_t dev)
550 {
551 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
552 	struct ahci_channel *ch = device_get_softc(dev);
553 	struct cam_devq *devq;
554 	int rid, error;
555 
556 	ch->dev = dev;
557 	ch->unit = (intptr_t)device_get_ivars(dev);
558 	ch->caps = ctlr->caps;
559 	ch->caps2 = ctlr->caps2;
560 	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
561 	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
562 	resource_int_value(device_get_name(dev),
563 	    device_get_unit(dev), "pm_level", &ch->pm_level);
564 	if (ch->pm_level > 3)
565 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
566 	/* Limit speed for my onboard JMicron external port.
567 	 * It is not eSATA really. */
568 	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
569 	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
570 	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
571 	    ch->unit == 0)
572 		ch->sata_rev = 1;
573 	resource_int_value(device_get_name(dev),
574 	    device_get_unit(dev), "sata_rev", &ch->sata_rev);
575 	rid = ch->unit;
576 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
577 	    &rid, RF_ACTIVE)))
578 		return (ENXIO);
579 	ahci_dmainit(dev);
580 	ahci_slotsalloc(dev);
581 	ahci_ch_resume(dev);
582 	mtx_lock(&ch->mtx);
583 	rid = ATA_IRQ_RID;
584 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
585 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
586 		bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
587 		device_printf(dev, "Unable to map interrupt\n");
588 		return (ENXIO);
589 	}
590 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
591 	    ahci_ch_intr_locked, dev, &ch->ih))) {
592 		device_printf(dev, "Unable to setup interrupt\n");
593 		error = ENXIO;
594 		goto err1;
595 	}
596 	/* Create the device queue for our SIM. */
597 	devq = cam_simq_alloc(ch->numslots);
598 	if (devq == NULL) {
599 		device_printf(dev, "Unable to allocate simq\n");
600 		error = ENOMEM;
601 		goto err1;
602 	}
603 	/* Construct SIM entry */
604 	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
605 	    device_get_unit(dev), &ch->mtx, ch->numslots, 0, devq);
606 	if (ch->sim == NULL) {
607 		device_printf(dev, "unable to allocate sim\n");
608 		error = ENOMEM;
609 		goto err2;
610 	}
611 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
612 		device_printf(dev, "unable to register xpt bus\n");
613 		error = ENXIO;
614 		goto err2;
615 	}
616 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
617 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
618 		device_printf(dev, "unable to create path\n");
619 		error = ENXIO;
620 		goto err3;
621 	}
622 	if (ch->pm_level > 3) {
623 		callout_reset(&ch->pm_timer,
624 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
625 		    ahci_ch_pm, dev);
626 	}
627 	mtx_unlock(&ch->mtx);
628 	return (0);
629 
630 err3:
631 	xpt_bus_deregister(cam_sim_path(ch->sim));
632 err2:
633 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
634 err1:
635 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
636 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
637 	mtx_unlock(&ch->mtx);
638 	return (error);
639 }
640 
641 static int
642 ahci_ch_detach(device_t dev)
643 {
644 	struct ahci_channel *ch = device_get_softc(dev);
645 
646 	mtx_lock(&ch->mtx);
647 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
648 	xpt_free_path(ch->path);
649 	xpt_bus_deregister(cam_sim_path(ch->sim));
650 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
651 	mtx_unlock(&ch->mtx);
652 
653 	if (ch->pm_level > 3)
654 		callout_drain(&ch->pm_timer);
655 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
656 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
657 
658 	ahci_ch_suspend(dev);
659 	ahci_slotsfree(dev);
660 	ahci_dmafini(dev);
661 
662 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
663 	mtx_destroy(&ch->mtx);
664 	return (0);
665 }
666 
667 static int
668 ahci_ch_suspend(device_t dev)
669 {
670 	struct ahci_channel *ch = device_get_softc(dev);
671 
672 	/* Disable port interrupts. */
673 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
674 	/* Reset command register. */
675 	ahci_stop(dev);
676 	ahci_stop_fr(dev);
677 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
678 	/* Allow everything, including partial and slumber modes. */
679 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
680 	/* Request slumber mode transition and give some time to get there. */
681 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
682 	DELAY(100);
683 	/* Disable PHY. */
684 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
685 	return (0);
686 }
687 
688 static int
689 ahci_ch_resume(device_t dev)
690 {
691 	struct ahci_channel *ch = device_get_softc(dev);
692 	uint64_t work;
693 
694 	/* Disable port interrupts */
695 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
696 	/* Setup work areas */
697 	work = ch->dma.work_bus + AHCI_CL_OFFSET;
698 	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
699 	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
700 	work = ch->dma.rfis_bus;
701 	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
702 	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
703 	/* Activate the channel and power/spin up device */
704 	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
705 	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
706 	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
707 	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
708 	ahci_start_fr(dev);
709 	ahci_start(dev);
710 	return (0);
711 }
712 
713 devclass_t ahcich_devclass;
714 static device_method_t ahcich_methods[] = {
715 	DEVMETHOD(device_probe,     ahci_ch_probe),
716 	DEVMETHOD(device_attach,    ahci_ch_attach),
717 	DEVMETHOD(device_detach,    ahci_ch_detach),
718 	DEVMETHOD(device_suspend,   ahci_ch_suspend),
719 	DEVMETHOD(device_resume,    ahci_ch_resume),
720 	{ 0, 0 }
721 };
722 static driver_t ahcich_driver = {
723         "ahcich",
724         ahcich_methods,
725         sizeof(struct ahci_channel)
726 };
727 DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahci_devclass, 0, 0);
728 
729 struct ahci_dc_cb_args {
730 	bus_addr_t maddr;
731 	int error;
732 };
733 
734 static void
735 ahci_dmainit(device_t dev)
736 {
737 	struct ahci_channel *ch = device_get_softc(dev);
738 	struct ahci_dc_cb_args dcba;
739 
740 	if (ch->caps & AHCI_CAP_64BIT)
741 		ch->dma.max_address = BUS_SPACE_MAXADDR;
742 	else
743 		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
744 	/* Command area. */
745 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
746 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
747 	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
748 	    0, NULL, NULL, &ch->dma.work_tag))
749 		goto error;
750 	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
751 	    &ch->dma.work_map))
752 		goto error;
753 	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
754 	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
755 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
756 		goto error;
757 	}
758 	ch->dma.work_bus = dcba.maddr;
759 	/* FIS receive area. */
760 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 4096, 0,
761 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
762 	    NULL, NULL, 4096, 1, 4096,
763 	    0, NULL, NULL, &ch->dma.rfis_tag))
764 		goto error;
765 	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
766 	    &ch->dma.rfis_map))
767 		goto error;
768 	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
769 	    4096, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
770 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
771 		goto error;
772 	}
773 	ch->dma.rfis_bus = dcba.maddr;
774 	/* Data area. */
775 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
776 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
777 	    NULL, NULL,
778 	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
779 	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
780 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
781 		goto error;
782 	}
783 	return;
784 
785 error:
786 	device_printf(dev, "WARNING - DMA initialization failed\n");
787 	ahci_dmafini(dev);
788 }
789 
790 static void
791 ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
792 {
793 	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
794 
795 	if (!(dcba->error = error))
796 		dcba->maddr = segs[0].ds_addr;
797 }
798 
799 static void
800 ahci_dmafini(device_t dev)
801 {
802 	struct ahci_channel *ch = device_get_softc(dev);
803 
804 	if (ch->dma.data_tag) {
805 		bus_dma_tag_destroy(ch->dma.data_tag);
806 		ch->dma.data_tag = NULL;
807 	}
808 	if (ch->dma.rfis_bus) {
809 		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
810 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
811 		ch->dma.rfis_bus = 0;
812 		ch->dma.rfis_map = NULL;
813 		ch->dma.rfis = NULL;
814 	}
815 	if (ch->dma.work_bus) {
816 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
817 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
818 		ch->dma.work_bus = 0;
819 		ch->dma.work_map = NULL;
820 		ch->dma.work = NULL;
821 	}
822 	if (ch->dma.work_tag) {
823 		bus_dma_tag_destroy(ch->dma.work_tag);
824 		ch->dma.work_tag = NULL;
825 	}
826 }
827 
828 static void
829 ahci_slotsalloc(device_t dev)
830 {
831 	struct ahci_channel *ch = device_get_softc(dev);
832 	int i;
833 
834 	/* Alloc and setup command/dma slots */
835 	bzero(ch->slot, sizeof(ch->slot));
836 	for (i = 0; i < ch->numslots; i++) {
837 		struct ahci_slot *slot = &ch->slot[i];
838 
839 		slot->dev = dev;
840 		slot->slot = i;
841 		slot->state = AHCI_SLOT_EMPTY;
842 		slot->ccb = NULL;
843 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
844 
845 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
846 			device_printf(ch->dev, "FAILURE - create data_map\n");
847 	}
848 }
849 
850 static void
851 ahci_slotsfree(device_t dev)
852 {
853 	struct ahci_channel *ch = device_get_softc(dev);
854 	int i;
855 
856 	/* Free all dma slots */
857 	for (i = 0; i < ch->numslots; i++) {
858 		struct ahci_slot *slot = &ch->slot[i];
859 
860 		callout_drain(&slot->timeout);
861 		if (slot->dma.data_map) {
862 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
863 			slot->dma.data_map = NULL;
864 		}
865 	}
866 }
867 
868 static void
869 ahci_phy_check_events(device_t dev)
870 {
871 	struct ahci_channel *ch = device_get_softc(dev);
872 	u_int32_t error = ATA_INL(ch->r_mem, AHCI_P_SERR);
873 
874 	/* Clear error bits/interrupt */
875 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, error);
876 	/* If we have a connection event, deal with it */
877 	if ((error & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
878 		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
879 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
880 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
881 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
882 			if (bootverbose)
883 				device_printf(dev, "CONNECT requested\n");
884 			ahci_reset(dev);
885 		} else {
886 			if (bootverbose)
887 				device_printf(dev, "DISCONNECT requested\n");
888 			ch->devices = 0;
889 		}
890 	}
891 }
892 
893 static void
894 ahci_notify_events(device_t dev, u_int32_t status)
895 {
896 	struct ahci_channel *ch = device_get_softc(dev);
897 	struct cam_path *dpath;
898 	int i;
899 
900 	ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
901 	if (bootverbose)
902 		device_printf(dev, "SNTF 0x%04x\n", status);
903 	for (i = 0; i < 16; i++) {
904 		if ((status & (1 << i)) == 0)
905 			continue;
906 		if (xpt_create_path(&dpath, NULL,
907 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
908 			xpt_async(AC_SCSI_AEN, dpath, NULL);
909 			xpt_free_path(dpath);
910 		}
911 	}
912 }
913 
914 static void
915 ahci_ch_intr_locked(void *data)
916 {
917 	device_t dev = (device_t)data;
918 	struct ahci_channel *ch = device_get_softc(dev);
919 
920 	mtx_lock(&ch->mtx);
921 	ahci_ch_intr(data);
922 	mtx_unlock(&ch->mtx);
923 }
924 
925 static void
926 ahci_ch_pm(void *arg)
927 {
928 	device_t dev = (device_t)arg;
929 	struct ahci_channel *ch = device_get_softc(dev);
930 	uint32_t work;
931 
932 	if (ch->numrslots != 0)
933 		return;
934 	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
935 	if (ch->pm_level == 4)
936 		work |= AHCI_P_CMD_PARTIAL;
937 	else
938 		work |= AHCI_P_CMD_SLUMBER;
939 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
940 }
941 
942 static void
943 ahci_ch_intr(void *data)
944 {
945 	device_t dev = (device_t)data;
946 	struct ahci_channel *ch = device_get_softc(dev);
947 	uint32_t istatus, sstatus, cstatus, sntf = 0, ok, err;
948 	enum ahci_err_type et;
949 	int i, ccs, ncq_err = 0;
950 
951 	/* Read and clear interrupt statuses. */
952 	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
953 	if (istatus == 0)
954 		return;
955 	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
956 	/* Read command statuses. */
957 	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
958 	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
959 	if ((istatus & AHCI_P_IX_SDB) && (ch->caps & AHCI_CAP_SSNTF))
960 		sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
961 	/* Process PHY events */
962 	if (istatus & (AHCI_P_IX_PRC | AHCI_P_IX_PC))
963 		ahci_phy_check_events(dev);
964 	/* Process command errors */
965 	if (istatus & (AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF |
966 		       AHCI_P_IX_TFE | AHCI_P_IX_OF)) {
967 //device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
968 //    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
969 //    ATA_INL(ch->r_mem, AHCI_P_SERR));
970 		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
971 		    >> AHCI_P_CMD_CCS_SHIFT;
972 		err = ch->rslots & (cstatus | sstatus);
973 		/* Kick controller into sane state */
974 		ahci_stop(dev);
975 		ahci_start(dev);
976 	} else {
977 		ccs = 0;
978 		err = 0;
979 	}
980 	/* Complete all successfull commands. */
981 	ok = ch->rslots & ~(cstatus | sstatus);
982 	for (i = 0; i < ch->numslots; i++) {
983 		if ((ok >> i) & 1)
984 			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
985 	}
986 	/* On error, complete the rest of commands with error statuses. */
987 	if (err) {
988 		if (!ch->readlog)
989 			xpt_freeze_simq(ch->sim, ch->numrslots);
990 		if (ch->frozen) {
991 			union ccb *fccb = ch->frozen;
992 			ch->frozen = NULL;
993 			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
994 			xpt_done(fccb);
995 		}
996 		for (i = 0; i < ch->numslots; i++) {
997 			/* XXX: reqests in loading state. */
998 			if (((err >> i) & 1) == 0)
999 				continue;
1000 			if (istatus & AHCI_P_IX_TFE) {
1001 				/* Task File Error */
1002 				if (ch->numtslots == 0) {
1003 					/* Untagged operation. */
1004 					if (i == ccs)
1005 						et = AHCI_ERR_TFE;
1006 					else
1007 						et = AHCI_ERR_INNOCENT;
1008 				} else {
1009 					/* Tagged operation. */
1010 					et = AHCI_ERR_NCQ;
1011 					ncq_err = 1;
1012 				}
1013 			} else if (istatus & AHCI_P_IX_IF) {
1014 				/* SATA error */
1015 				et = AHCI_ERR_SATA;
1016 			} else
1017 				et = AHCI_ERR_INVALID;
1018 			ahci_end_transaction(&ch->slot[i], et);
1019 		}
1020 		if (ncq_err)
1021 			ahci_issue_read_log(dev);
1022 	}
1023 	/* Process NOTIFY events */
1024 	if (sntf)
1025 		ahci_notify_events(dev, sntf);
1026 }
1027 
1028 /* Must be called with channel locked. */
1029 static int
1030 ahci_check_collision(device_t dev, union ccb *ccb)
1031 {
1032 	struct ahci_channel *ch = device_get_softc(dev);
1033 
1034 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1035 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1036 		/* Tagged command while untagged are active. */
1037 		if (ch->numrslots != 0 && ch->numtslots == 0)
1038 			return (1);
1039 		/* Tagged command while tagged to other target is active. */
1040 		if (ch->numtslots != 0 &&
1041 		    ch->taggedtarget != ccb->ccb_h.target_id)
1042 			return (1);
1043 	} else {
1044 		/* Untagged command while tagged are active. */
1045 		if (ch->numrslots != 0 && ch->numtslots != 0)
1046 			return (1);
1047 	}
1048 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1049 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1050 		/* Atomic command while anything active. */
1051 		if (ch->numrslots != 0)
1052 			return (1);
1053 	}
1054        /* We have some atomic command running. */
1055        if (ch->aslots != 0)
1056                return (1);
1057 	return (0);
1058 }
1059 
1060 /* Must be called with channel locked. */
1061 static void
1062 ahci_begin_transaction(device_t dev, union ccb *ccb)
1063 {
1064 	struct ahci_channel *ch = device_get_softc(dev);
1065 	struct ahci_slot *slot;
1066 	int tag;
1067 
1068 	/* Choose empty slot. */
1069 	tag = ch->lastslot;
1070 	while (ch->slot[tag].state != AHCI_SLOT_EMPTY) {
1071 		if (++tag >= ch->numslots)
1072 			tag = 0;
1073 		KASSERT(tag != ch->lastslot, ("ahci: ALL SLOTS BUSY!"));
1074 	}
1075 	ch->lastslot = tag;
1076 	/* Occupy chosen slot. */
1077 	slot = &ch->slot[tag];
1078 	slot->ccb = ccb;
1079 	/* Stop PM timer. */
1080 	if (ch->numrslots == 0 && ch->pm_level > 3)
1081 		callout_stop(&ch->pm_timer);
1082 	/* Update channel stats. */
1083 	ch->numrslots++;
1084 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1085 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1086 		ch->numtslots++;
1087 		ch->taggedtarget = ccb->ccb_h.target_id;
1088 	}
1089 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1090 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1091 		ch->aslots |= (1 << slot->slot);
1092 	slot->dma.nsegs = 0;
1093 	/* If request moves data, setup and load SG list */
1094 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1095 		void *buf;
1096 		bus_size_t size;
1097 
1098 		slot->state = AHCI_SLOT_LOADING;
1099 		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1100 			buf = ccb->ataio.data_ptr;
1101 			size = ccb->ataio.dxfer_len;
1102 		} else {
1103 			buf = ccb->csio.data_ptr;
1104 			size = ccb->csio.dxfer_len;
1105 		}
1106 		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1107 		    buf, size, ahci_dmasetprd, slot, 0);
1108 	} else
1109 		ahci_execute_transaction(slot);
1110 }
1111 
1112 /* Locked by busdma engine. */
1113 static void
1114 ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1115 {
1116 	struct ahci_slot *slot = arg;
1117 	struct ahci_channel *ch = device_get_softc(slot->dev);
1118 	struct ahci_cmd_tab *ctp;
1119 	struct ahci_dma_prd *prd;
1120 	int i;
1121 
1122 	if (error) {
1123 		device_printf(slot->dev, "DMA load error\n");
1124 		if (!ch->readlog)
1125 			xpt_freeze_simq(ch->sim, 1);
1126 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1127 		return;
1128 	}
1129 	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1130 	/* Get a piece of the workspace for this request */
1131 	ctp = (struct ahci_cmd_tab *)
1132 		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1133 	/* Fill S/G table */
1134 	prd = &ctp->prd_tab[0];
1135 	for (i = 0; i < nsegs; i++) {
1136 		prd[i].dba = htole64(segs[i].ds_addr);
1137 		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1138 	}
1139 	slot->dma.nsegs = nsegs;
1140 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1141 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1142 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1143 	ahci_execute_transaction(slot);
1144 }
1145 
1146 /* Must be called with channel locked. */
1147 static void
1148 ahci_execute_transaction(struct ahci_slot *slot)
1149 {
1150 	device_t dev = slot->dev;
1151 	struct ahci_channel *ch = device_get_softc(dev);
1152 	struct ahci_cmd_tab *ctp;
1153 	struct ahci_cmd_list *clp;
1154 	union ccb *ccb = slot->ccb;
1155 	int port = ccb->ccb_h.target_id & 0x0f;
1156 	int fis_size;
1157 
1158 	/* Get a piece of the workspace for this request */
1159 	ctp = (struct ahci_cmd_tab *)
1160 		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1161 	/* Setup the FIS for this request */
1162 	if (!(fis_size = ahci_setup_fis(ctp, ccb, slot->slot))) {
1163 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1164 		if (!ch->readlog)
1165 			xpt_freeze_simq(ch->sim, 1);
1166 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1167 		return;
1168 	}
1169 	/* Setup the command list entry */
1170 	clp = (struct ahci_cmd_list *)
1171 	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1172 	clp->prd_length = slot->dma.nsegs;
1173 	clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1174 		     (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1175 		      (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1176 		     (fis_size / sizeof(u_int32_t)) |
1177 		     (port << 12);
1178 	/* Special handling for Soft Reset command. */
1179 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1180 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1181 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1182 		/* Kick controller into sane state */
1183 		ahci_stop(dev);
1184 		ahci_clo(dev);
1185 		ahci_start(dev);
1186 		clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1187 	}
1188 	clp->bytecount = 0;
1189 	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1190 				  (AHCI_CT_SIZE * slot->slot));
1191 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1192 	    BUS_DMASYNC_PREWRITE);
1193 	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1194 	    BUS_DMASYNC_PREREAD);
1195 	/* Set ACTIVE bit for NCQ commands. */
1196 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1197 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1198 		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1199 	}
1200 	/* Issue command to the controller. */
1201 	slot->state = AHCI_SLOT_RUNNING;
1202 	ch->rslots |= (1 << slot->slot);
1203 	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1204 	/* Device reset commands doesn't interrupt. Poll them. */
1205 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1206 	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1207 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1208 		int count, timeout = ccb->ccb_h.timeout;
1209 		enum ahci_err_type et = AHCI_ERR_NONE;
1210 
1211 		for (count = 0; count < timeout; count++) {
1212 			DELAY(1000);
1213 			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1214 				break;
1215 			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1216 				device_printf(ch->dev,
1217 				    "Poll error on slot %d, TFD: %04x\n",
1218 				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1219 				et = AHCI_ERR_TFE;
1220 				break;
1221 			}
1222 		}
1223 		if (timeout && (count >= timeout)) {
1224 			device_printf(ch->dev,
1225 			    "Poll timeout on slot %d\n", slot->slot);
1226 			et = AHCI_ERR_TIMEOUT;
1227 		}
1228 		if (et != AHCI_ERR_NONE) {
1229 			/* Kick controller into sane state */
1230 			ahci_stop(ch->dev);
1231 			ahci_start(ch->dev);
1232 			xpt_freeze_simq(ch->sim, 1);
1233 		}
1234 		ahci_end_transaction(slot, et);
1235 		return;
1236 	}
1237 	/* Start command execution timeout */
1238 	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 1000,
1239 	    (timeout_t*)ahci_timeout, slot);
1240 	return;
1241 }
1242 
1243 /* Locked by callout mechanism. */
1244 static void
1245 ahci_timeout(struct ahci_slot *slot)
1246 {
1247 	device_t dev = slot->dev;
1248 	struct ahci_channel *ch = device_get_softc(dev);
1249 	int i;
1250 
1251 	/* Check for stale timeout. */
1252 	if (slot->state != AHCI_SLOT_RUNNING)
1253 		return;
1254 
1255 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1256 	/* Kick controller into sane state. */
1257 	ahci_stop(ch->dev);
1258 	ahci_start(ch->dev);
1259 
1260 	if (!ch->readlog)
1261 		xpt_freeze_simq(ch->sim, ch->numrslots);
1262 	/* Handle command with timeout. */
1263 	ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1264 	/* Handle the rest of commands. */
1265 	if (ch->frozen) {
1266 		union ccb *fccb = ch->frozen;
1267 		ch->frozen = NULL;
1268 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1269 		xpt_done(fccb);
1270 	}
1271 	for (i = 0; i < ch->numslots; i++) {
1272 		/* Do we have a running request on slot? */
1273 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1274 			continue;
1275 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1276 	}
1277 }
1278 
1279 /* Must be called with channel locked. */
1280 static void
1281 ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1282 {
1283 	device_t dev = slot->dev;
1284 	struct ahci_channel *ch = device_get_softc(dev);
1285 	union ccb *ccb = slot->ccb;
1286 
1287 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1288 	    BUS_DMASYNC_POSTWRITE);
1289 	/* Read result registers to the result struct
1290 	 * May be incorrect if several commands finished same time,
1291 	 * so read only when sure or have to.
1292 	 */
1293 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1294 		struct ata_res *res = &ccb->ataio.res;
1295 
1296 		if ((et == AHCI_ERR_TFE) ||
1297 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1298 			u_int8_t *fis = ch->dma.rfis + 0x40;
1299 			uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1300 
1301 			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1302 			    BUS_DMASYNC_POSTREAD);
1303 			res->status = tfd;
1304 			res->error = tfd >> 8;
1305 			res->lba_low = fis[4];
1306 			res->lba_mid = fis[5];
1307 			res->lba_high = fis[6];
1308 			res->device = fis[7];
1309 			res->lba_low_exp = fis[8];
1310 			res->lba_mid_exp = fis[9];
1311 			res->lba_high_exp = fis[10];
1312 			res->sector_count = fis[12];
1313 			res->sector_count_exp = fis[13];
1314 		} else
1315 			bzero(res, sizeof(*res));
1316 	}
1317 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1318 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1319 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1320 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1321 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1322 	}
1323 	/* Set proper result status. */
1324 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1325 	if (et != AHCI_ERR_NONE)
1326 		ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1327 	switch (et) {
1328 	case AHCI_ERR_NONE:
1329 		ccb->ccb_h.status |= CAM_REQ_CMP;
1330 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1331 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1332 		break;
1333 	case AHCI_ERR_INVALID:
1334 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1335 		break;
1336 	case AHCI_ERR_INNOCENT:
1337 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1338 		break;
1339 	case AHCI_ERR_TFE:
1340 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1341 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1342 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1343 		} else {
1344 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1345 		}
1346 		break;
1347 	case AHCI_ERR_SATA:
1348 			ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1349 		break;
1350 	case AHCI_ERR_TIMEOUT:
1351 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1352 		break;
1353 	case AHCI_ERR_NCQ:
1354 		ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1355 	default:
1356 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1357 	}
1358 	/* Free slot. */
1359 	ch->rslots &= ~(1 << slot->slot);
1360 	ch->aslots &= ~(1 << slot->slot);
1361 	slot->state = AHCI_SLOT_EMPTY;
1362 	slot->ccb = NULL;
1363 	/* Update channel stats. */
1364 	ch->numrslots--;
1365 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1366 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1367 		ch->numtslots--;
1368 	}
1369 	/* If it was first request of reset sequence and there is no error,
1370 	 * proceed to second request. */
1371 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1372 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1373 	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1374 	    et == AHCI_ERR_NONE) {
1375 		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1376 		ahci_begin_transaction(dev, ccb);
1377 		return;
1378 	}
1379 	/* If it was NCQ command error, put result on hold. */
1380 	if (et == AHCI_ERR_NCQ) {
1381 		ch->hold[slot->slot] = ccb;
1382 	} else if (ch->readlog)	/* If it was our READ LOG command - process it. */
1383 		ahci_process_read_log(dev, ccb);
1384 	else
1385 		xpt_done(ccb);
1386 	/* Unfreeze frozen command. */
1387 	if (ch->frozen && ch->numrslots == 0) {
1388 		union ccb *fccb = ch->frozen;
1389 		ch->frozen = NULL;
1390 		ahci_begin_transaction(dev, fccb);
1391 		xpt_release_simq(ch->sim, TRUE);
1392 	}
1393 	/* Start PM timer. */
1394 	if (ch->numrslots == 0 && ch->pm_level > 3) {
1395 		callout_schedule(&ch->pm_timer,
1396 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1397 	}
1398 }
1399 
1400 static void
1401 ahci_issue_read_log(device_t dev)
1402 {
1403 	struct ahci_channel *ch = device_get_softc(dev);
1404 	union ccb *ccb;
1405 	struct ccb_ataio *ataio;
1406 	int i;
1407 
1408 	ch->readlog = 1;
1409 	/* Find some holden command. */
1410 	for (i = 0; i < ch->numslots; i++) {
1411 		if (ch->hold[i])
1412 			break;
1413 	}
1414 	ccb = xpt_alloc_ccb_nowait();
1415 	if (ccb == NULL) {
1416 		device_printf(dev, "Unable allocate READ LOG command");
1417 		return; /* XXX */
1418 	}
1419 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1420 	ccb->ccb_h.func_code = XPT_ATA_IO;
1421 	ccb->ccb_h.flags = CAM_DIR_IN;
1422 	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1423 	ataio = &ccb->ataio;
1424 	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1425 	if (ataio->data_ptr == NULL) {
1426 		device_printf(dev, "Unable allocate memory for READ LOG command");
1427 		return; /* XXX */
1428 	}
1429 	ataio->dxfer_len = 512;
1430 	bzero(&ataio->cmd, sizeof(ataio->cmd));
1431 	ataio->cmd.flags = CAM_ATAIO_48BIT;
1432 	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1433 	ataio->cmd.sector_count = 1;
1434 	ataio->cmd.sector_count_exp = 0;
1435 	ataio->cmd.lba_low = 0x10;
1436 	ataio->cmd.lba_mid = 0;
1437 	ataio->cmd.lba_mid_exp = 0;
1438 
1439 	ahci_begin_transaction(dev, ccb);
1440 }
1441 
1442 static void
1443 ahci_process_read_log(device_t dev, union ccb *ccb)
1444 {
1445 	struct ahci_channel *ch = device_get_softc(dev);
1446 	uint8_t *data;
1447 	struct ata_res *res;
1448 	int i;
1449 
1450 	ch->readlog = 0;
1451 
1452 	data = ccb->ataio.data_ptr;
1453 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1454 	    (data[0] & 0x80) == 0) {
1455 		for (i = 0; i < ch->numslots; i++) {
1456 			if (!ch->hold[i])
1457 				continue;
1458 			if ((data[0] & 0x1F) == i) {
1459 				res = &ch->hold[i]->ataio.res;
1460 				res->status = data[2];
1461 				res->error = data[3];
1462 				res->lba_low = data[4];
1463 				res->lba_mid = data[5];
1464 				res->lba_high = data[6];
1465 				res->device = data[7];
1466 				res->lba_low_exp = data[8];
1467 				res->lba_mid_exp = data[9];
1468 				res->lba_high_exp = data[10];
1469 				res->sector_count = data[12];
1470 				res->sector_count_exp = data[13];
1471 			} else {
1472 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1473 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1474 			}
1475 			xpt_done(ch->hold[i]);
1476 			ch->hold[i] = NULL;
1477 		}
1478 	} else {
1479 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1480 			device_printf(dev, "Error while READ LOG EXT\n");
1481 		else if ((data[0] & 0x80) == 0) {
1482 			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1483 		}
1484 		for (i = 0; i < ch->numslots; i++) {
1485 			if (!ch->hold[i])
1486 				continue;
1487 			xpt_done(ch->hold[i]);
1488 			ch->hold[i] = NULL;
1489 		}
1490 	}
1491 	free(ccb->ataio.data_ptr, M_AHCI);
1492 	xpt_free_ccb(ccb);
1493 }
1494 
1495 static void
1496 ahci_start(device_t dev)
1497 {
1498 	struct ahci_channel *ch = device_get_softc(dev);
1499 	u_int32_t cmd;
1500 
1501 	/* Clear SATA error register */
1502 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
1503 	/* Clear any interrupts pending on this channel */
1504 	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
1505 	/* Start operations on this channel */
1506 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1507 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
1508 	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
1509 }
1510 
1511 static void
1512 ahci_stop(device_t dev)
1513 {
1514 	struct ahci_channel *ch = device_get_softc(dev);
1515 	u_int32_t cmd;
1516 	int timeout;
1517 
1518 	/* Kill all activity on this channel */
1519 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1520 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
1521 	/* Wait for activity stop. */
1522 	timeout = 0;
1523 	do {
1524 		DELAY(1000);
1525 		if (timeout++ > 1000) {
1526 			device_printf(dev, "stopping AHCI engine failed\n");
1527 			break;
1528 		}
1529 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
1530 }
1531 
1532 static void
1533 ahci_clo(device_t dev)
1534 {
1535 	struct ahci_channel *ch = device_get_softc(dev);
1536 	u_int32_t cmd;
1537 	int timeout;
1538 
1539 	/* Issue Command List Override if supported */
1540 	if (ch->caps & AHCI_CAP_SCLO) {
1541 		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1542 		cmd |= AHCI_P_CMD_CLO;
1543 		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
1544 		timeout = 0;
1545 		do {
1546 			DELAY(1000);
1547 			if (timeout++ > 1000) {
1548 			    device_printf(dev, "executing CLO failed\n");
1549 			    break;
1550 			}
1551 		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
1552 	}
1553 }
1554 
1555 static void
1556 ahci_stop_fr(device_t dev)
1557 {
1558 	struct ahci_channel *ch = device_get_softc(dev);
1559 	u_int32_t cmd;
1560 	int timeout;
1561 
1562 	/* Kill all FIS reception on this channel */
1563 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1564 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
1565 	/* Wait for FIS reception stop. */
1566 	timeout = 0;
1567 	do {
1568 		DELAY(1000);
1569 		if (timeout++ > 1000) {
1570 			device_printf(dev, "stopping AHCI FR engine failed\n");
1571 			break;
1572 		}
1573 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
1574 }
1575 
1576 static void
1577 ahci_start_fr(device_t dev)
1578 {
1579 	struct ahci_channel *ch = device_get_softc(dev);
1580 	u_int32_t cmd;
1581 
1582 	/* Start FIS reception on this channel */
1583 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1584 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
1585 }
1586 
1587 static int
1588 ahci_wait_ready(device_t dev, int t)
1589 {
1590 	struct ahci_channel *ch = device_get_softc(dev);
1591 	int timeout = 0;
1592 	uint32_t val;
1593 
1594 	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
1595 	    (ATA_S_BUSY | ATA_S_DRQ)) {
1596 		DELAY(1000);
1597 		if (timeout++ > t) {
1598 			device_printf(dev, "port is not ready (timeout %dms) "
1599 			    "tfd = %08x\n", t, val);
1600 			return (EBUSY);
1601 		}
1602 	}
1603 	if (bootverbose)
1604 		device_printf(dev, "ready wait time=%dms\n", timeout);
1605 	return (0);
1606 }
1607 
1608 static void
1609 ahci_reset(device_t dev)
1610 {
1611 	struct ahci_channel *ch = device_get_softc(dev);
1612 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
1613 	int i;
1614 
1615 	if (bootverbose)
1616 		device_printf(dev, "AHCI reset...\n");
1617 	xpt_freeze_simq(ch->sim, ch->numrslots);
1618 	/* Requeue freezed command. */
1619 	if (ch->frozen) {
1620 		union ccb *fccb = ch->frozen;
1621 		ch->frozen = NULL;
1622 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1623 		xpt_done(fccb);
1624 	}
1625 	/* Kill the engine and requeue all running commands. */
1626 	ahci_stop(dev);
1627 	for (i = 0; i < ch->numslots; i++) {
1628 		/* Do we have a running request on slot? */
1629 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1630 			continue;
1631 		/* XXX; Commands in loading state. */
1632 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1633 	}
1634 	/* Disable port interrupts */
1635 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1636 	/* Reset and reconnect PHY, */
1637 	if (!ahci_sata_phy_reset(dev, 0)) {
1638 		if (bootverbose)
1639 			device_printf(dev,
1640 			    "AHCI reset done: phy reset found no device\n");
1641 		ch->devices = 0;
1642 		/* Enable wanted port interrupts */
1643 		ATA_OUTL(ch->r_mem, AHCI_P_IE,
1644 		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
1645 		return;
1646 	}
1647 	/* Wait for clearing busy status. */
1648 	if (ahci_wait_ready(dev, 10000)) {
1649 		device_printf(dev, "device ready timeout\n");
1650 		ahci_clo(dev);
1651 	}
1652 	ahci_start(dev);
1653 	ch->devices = 1;
1654 	/* Enable wanted port interrupts */
1655 	ATA_OUTL(ch->r_mem, AHCI_P_IE,
1656 	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
1657 	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
1658 	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
1659 	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
1660 	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
1661 	if (bootverbose)
1662 		device_printf(dev, "AHCI reset done: device found\n");
1663 	/* Tell the XPT about the event */
1664 	xpt_async(AC_BUS_RESET, ch->path, NULL);
1665 }
1666 
1667 static int
1668 ahci_setup_fis(struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
1669 {
1670 	u_int8_t *fis = &ctp->cfis[0];
1671 
1672 	bzero(ctp->cfis, 64);
1673 	fis[0] = 0x27;  		/* host to device */
1674 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
1675 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1676 		fis[1] |= 0x80;
1677 		fis[2] = ATA_PACKET_CMD;
1678 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
1679 			fis[3] = ATA_F_DMA;
1680 		else {
1681 			fis[5] = ccb->csio.dxfer_len;
1682 		        fis[6] = ccb->csio.dxfer_len >> 8;
1683 		}
1684 		fis[7] = ATA_D_LBA;
1685 		fis[15] = ATA_A_4BIT;
1686 		bzero(ctp->acmd, 32);
1687 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
1688 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
1689 		    ctp->acmd, ccb->csio.cdb_len);
1690 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
1691 		fis[1] |= 0x80;
1692 		fis[2] = ccb->ataio.cmd.command;
1693 		fis[3] = ccb->ataio.cmd.features;
1694 		fis[4] = ccb->ataio.cmd.lba_low;
1695 		fis[5] = ccb->ataio.cmd.lba_mid;
1696 		fis[6] = ccb->ataio.cmd.lba_high;
1697 		fis[7] = ccb->ataio.cmd.device;
1698 		fis[8] = ccb->ataio.cmd.lba_low_exp;
1699 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
1700 		fis[10] = ccb->ataio.cmd.lba_high_exp;
1701 		fis[11] = ccb->ataio.cmd.features_exp;
1702 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
1703 			fis[12] = tag << 3;
1704 			fis[13] = 0;
1705 		} else {
1706 			fis[12] = ccb->ataio.cmd.sector_count;
1707 			fis[13] = ccb->ataio.cmd.sector_count_exp;
1708 		}
1709 		fis[15] = ATA_A_4BIT;
1710 	} else {
1711 		fis[15] = ccb->ataio.cmd.control;
1712 	}
1713 	return (20);
1714 }
1715 
1716 static int
1717 ahci_sata_connect(struct ahci_channel *ch)
1718 {
1719 	u_int32_t status;
1720 	int timeout;
1721 
1722 	/* Wait up to 100ms for "connect well" */
1723 	for (timeout = 0; timeout < 100 ; timeout++) {
1724 		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1725 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1726 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1727 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
1728 			break;
1729 		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
1730 			if (bootverbose) {
1731 				device_printf(ch->dev, "SATA offline status=%08x\n",
1732 				    status);
1733 			}
1734 			return (0);
1735 		}
1736 		DELAY(1000);
1737 	}
1738 	if (timeout >= 100) {
1739 		if (bootverbose) {
1740 			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
1741 			    status);
1742 		}
1743 		return (0);
1744 	}
1745 	if (bootverbose) {
1746 		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
1747 		    timeout, status);
1748 	}
1749 	/* Clear SATA error register */
1750 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
1751 	return (1);
1752 }
1753 
1754 static int
1755 ahci_sata_phy_reset(device_t dev, int quick)
1756 {
1757 	struct ahci_channel *ch = device_get_softc(dev);
1758 	uint32_t val;
1759 
1760 	if (quick) {
1761 		val = ATA_INL(ch->r_mem, AHCI_P_SCTL);
1762 		if ((val & ATA_SC_DET_MASK) == ATA_SC_DET_IDLE)
1763 			return (ahci_sata_connect(ch));
1764 	}
1765 
1766 	if (bootverbose)
1767 		device_printf(dev, "hardware reset ...\n");
1768 	if (ch->sata_rev == 1)
1769 		val = ATA_SC_SPD_SPEED_GEN1;
1770 	else if (ch->sata_rev == 2)
1771 		val = ATA_SC_SPD_SPEED_GEN2;
1772 	else if (ch->sata_rev == 3)
1773 		val = ATA_SC_SPD_SPEED_GEN3;
1774 	else
1775 		val = 0;
1776 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
1777 	    ATA_SC_DET_RESET | val |
1778 	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
1779 	DELAY(5000);
1780 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
1781 	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
1782 	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
1783 	DELAY(5000);
1784 	return (ahci_sata_connect(ch));
1785 }
1786 
1787 static void
1788 ahciaction(struct cam_sim *sim, union ccb *ccb)
1789 {
1790 	device_t dev;
1791 	struct ahci_channel *ch;
1792 
1793 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
1794 	    ccb->ccb_h.func_code));
1795 
1796 	ch = (struct ahci_channel *)cam_sim_softc(sim);
1797 	dev = ch->dev;
1798 	switch (ccb->ccb_h.func_code) {
1799 	/* Common cases first */
1800 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
1801 	case XPT_SCSI_IO:
1802 		if (ch->devices == 0) {
1803 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1804 			xpt_done(ccb);
1805 			break;
1806 		}
1807 		/* Check for command collision. */
1808 		if (ahci_check_collision(dev, ccb)) {
1809 			/* Freeze command. */
1810 			ch->frozen = ccb;
1811 			/* We have only one frozen slot, so freeze simq also. */
1812 			xpt_freeze_simq(ch->sim, 1);
1813 			return;
1814 		}
1815 		ahci_begin_transaction(dev, ccb);
1816 		break;
1817 	case XPT_EN_LUN:		/* Enable LUN as a target */
1818 	case XPT_TARGET_IO:		/* Execute target I/O request */
1819 	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
1820 	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
1821 	case XPT_ABORT:			/* Abort the specified CCB */
1822 		/* XXX Implement */
1823 		ccb->ccb_h.status = CAM_REQ_INVALID;
1824 		xpt_done(ccb);
1825 		break;
1826 	case XPT_SET_TRAN_SETTINGS:
1827 	{
1828 		struct	ccb_trans_settings *cts = &ccb->cts;
1829 
1830 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM) {
1831 			ch->pm_present = cts->xport_specific.sata.pm_present;
1832 		}
1833 		ccb->ccb_h.status = CAM_REQ_CMP;
1834 		xpt_done(ccb);
1835 		break;
1836 	}
1837 	case XPT_GET_TRAN_SETTINGS:
1838 	/* Get default/user set transfer settings for the target */
1839 	{
1840 		struct	ccb_trans_settings *cts = &ccb->cts;
1841 		uint32_t status;
1842 
1843 		cts->protocol = PROTO_ATA;
1844 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
1845 		cts->transport = XPORT_SATA;
1846 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
1847 		cts->proto_specific.valid = 0;
1848 		cts->xport_specific.sata.valid = 0;
1849 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
1850 			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
1851 		else
1852 			status = ATA_INL(ch->r_mem, AHCI_P_SCTL) & ATA_SC_SPD_MASK;
1853 		if (status & ATA_SS_SPD_GEN3) {
1854 			cts->xport_specific.sata.bitrate = 600000;
1855 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1856 		} else if (status & ATA_SS_SPD_GEN2) {
1857 			cts->xport_specific.sata.bitrate = 300000;
1858 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1859 		} else if (status & ATA_SS_SPD_GEN1) {
1860 			cts->xport_specific.sata.bitrate = 150000;
1861 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_SPEED;
1862 		}
1863 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
1864 			cts->xport_specific.sata.pm_present =
1865 			    (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_PMA) ?
1866 			    1 : 0;
1867 		} else {
1868 			cts->xport_specific.sata.pm_present = ch->pm_present;
1869 		}
1870 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
1871 		ccb->ccb_h.status = CAM_REQ_CMP;
1872 		xpt_done(ccb);
1873 		break;
1874 	}
1875 #if 0
1876 	case XPT_CALC_GEOMETRY:
1877 	{
1878 		struct	  ccb_calc_geometry *ccg;
1879 		uint32_t size_mb;
1880 		uint32_t secs_per_cylinder;
1881 
1882 		ccg = &ccb->ccg;
1883 		size_mb = ccg->volume_size
1884 			/ ((1024L * 1024L) / ccg->block_size);
1885 		if (size_mb >= 1024 && (aha->extended_trans != 0)) {
1886 			if (size_mb >= 2048) {
1887 				ccg->heads = 255;
1888 				ccg->secs_per_track = 63;
1889 			} else {
1890 				ccg->heads = 128;
1891 				ccg->secs_per_track = 32;
1892 			}
1893 		} else {
1894 			ccg->heads = 64;
1895 			ccg->secs_per_track = 32;
1896 		}
1897 		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
1898 		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
1899 		ccb->ccb_h.status = CAM_REQ_CMP;
1900 		xpt_done(ccb);
1901 		break;
1902 	}
1903 #endif
1904 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
1905 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
1906 		ahci_reset(dev);
1907 		ccb->ccb_h.status = CAM_REQ_CMP;
1908 		xpt_done(ccb);
1909 		break;
1910 	case XPT_TERM_IO:		/* Terminate the I/O process */
1911 		/* XXX Implement */
1912 		ccb->ccb_h.status = CAM_REQ_INVALID;
1913 		xpt_done(ccb);
1914 		break;
1915 	case XPT_PATH_INQ:		/* Path routing inquiry */
1916 	{
1917 		struct ccb_pathinq *cpi = &ccb->cpi;
1918 
1919 		cpi->version_num = 1; /* XXX??? */
1920 		cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
1921 		if (ch->caps & AHCI_CAP_SPM)
1922 			cpi->hba_inquiry |= PI_SATAPM;
1923 		cpi->target_sprt = 0;
1924 		cpi->hba_misc = PIM_SEQSCAN;
1925 		cpi->hba_eng_cnt = 0;
1926 		if (ch->caps & AHCI_CAP_SPM)
1927 			cpi->max_target = 14;
1928 		else
1929 			cpi->max_target = 0;
1930 		cpi->max_lun = 0;
1931 		cpi->initiator_id = 0;
1932 		cpi->bus_id = cam_sim_bus(sim);
1933 		cpi->base_transfer_speed = 150000;
1934 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1935 		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
1936 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1937 		cpi->unit_number = cam_sim_unit(sim);
1938 		cpi->transport = XPORT_SATA;
1939 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
1940 		cpi->protocol = PROTO_ATA;
1941 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
1942 		cpi->maxio = MAXPHYS;
1943 		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
1944 		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
1945 			cpi->maxio = min(cpi->maxio, 128 * 512);
1946 		cpi->ccb_h.status = CAM_REQ_CMP;
1947 		xpt_done(ccb);
1948 		break;
1949 	}
1950 	default:
1951 		ccb->ccb_h.status = CAM_REQ_INVALID;
1952 		xpt_done(ccb);
1953 		break;
1954 	}
1955 }
1956 
1957 static void
1958 ahcipoll(struct cam_sim *sim)
1959 {
1960 	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
1961 
1962 	ahci_ch_intr(ch->dev);
1963 }
1964