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