ahci.c revision 311883
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 311883 2017-01-10 19:15:37Z 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
1126	mtx_lock(&ch->mtx);
1127	ahci_ch_intr_main(ch, istatus);
1128	mtx_unlock(&ch->mtx);
1129}
1130
1131static void
1132ahci_ch_intr_direct(void *arg)
1133{
1134	struct ahci_channel *ch = (struct ahci_channel *)arg;
1135	struct ccb_hdr *ccb_h;
1136	uint32_t istatus;
1137	STAILQ_HEAD(, ccb_hdr) tmp_doneq = STAILQ_HEAD_INITIALIZER(tmp_doneq);
1138
1139	/* Read interrupt statuses. */
1140	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1141
1142	mtx_lock(&ch->mtx);
1143	ch->batch = 1;
1144	ahci_ch_intr_main(ch, istatus);
1145	ch->batch = 0;
1146	/*
1147	 * Prevent the possibility of issues caused by processing the queue
1148	 * while unlocked below by moving the contents to a local queue.
1149	 */
1150	STAILQ_CONCAT(&tmp_doneq, &ch->doneq);
1151	mtx_unlock(&ch->mtx);
1152	while ((ccb_h = STAILQ_FIRST(&tmp_doneq)) != NULL) {
1153		STAILQ_REMOVE_HEAD(&tmp_doneq, sim_links.stqe);
1154		xpt_done_direct((union ccb *)ccb_h);
1155	}
1156}
1157
1158static void
1159ahci_ch_pm(void *arg)
1160{
1161	struct ahci_channel *ch = (struct ahci_channel *)arg;
1162	uint32_t work;
1163
1164	if (ch->numrslots != 0)
1165		return;
1166	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1167	if (ch->pm_level == 4)
1168		work |= AHCI_P_CMD_PARTIAL;
1169	else
1170		work |= AHCI_P_CMD_SLUMBER;
1171	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1172}
1173
1174static void
1175ahci_ch_intr_main(struct ahci_channel *ch, uint32_t istatus)
1176{
1177	uint32_t cstatus, serr = 0, sntf = 0, ok, err;
1178	enum ahci_err_type et;
1179	int i, ccs, port, reset = 0;
1180
1181	/* Clear interrupt statuses. */
1182	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1183	/* Read command statuses. */
1184	if (ch->numtslots != 0)
1185		cstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1186	else
1187		cstatus = 0;
1188	if (ch->numrslots != ch->numtslots)
1189		cstatus |= ATA_INL(ch->r_mem, AHCI_P_CI);
1190	/* Read SNTF in one of possible ways. */
1191	if ((istatus & AHCI_P_IX_SDB) &&
1192	    (ch->pm_present || ch->curr[0].atapi != 0)) {
1193		if (ch->caps & AHCI_CAP_SSNTF)
1194			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1195		else if (ch->fbs_enabled) {
1196			u_int8_t *fis = ch->dma.rfis + 0x58;
1197
1198			for (i = 0; i < 16; i++) {
1199				if (fis[1] & 0x80) {
1200					fis[1] &= 0x7f;
1201	    				sntf |= 1 << i;
1202	    			}
1203	    			fis += 256;
1204	    		}
1205		} else {
1206			u_int8_t *fis = ch->dma.rfis + 0x58;
1207
1208			if (fis[1] & 0x80)
1209				sntf = (1 << (fis[1] & 0x0f));
1210		}
1211	}
1212	/* Process PHY events */
1213	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1214	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1215		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1216		if (serr) {
1217			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1218			reset = ahci_phy_check_events(ch, serr);
1219		}
1220	}
1221	/* Process cold presence detection events */
1222	if ((istatus & AHCI_P_IX_CPD) && !reset)
1223		ahci_cpd_check_events(ch);
1224	/* Process command errors */
1225	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1226	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1227		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1228		    >> AHCI_P_CMD_CCS_SHIFT;
1229//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1230//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1231//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1232		port = -1;
1233		if (ch->fbs_enabled) {
1234			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1235			if (fbs & AHCI_P_FBS_SDE) {
1236				port = (fbs & AHCI_P_FBS_DWE)
1237				    >> AHCI_P_FBS_DWE_SHIFT;
1238			} else {
1239				for (i = 0; i < 16; i++) {
1240					if (ch->numrslotspd[i] == 0)
1241						continue;
1242					if (port == -1)
1243						port = i;
1244					else if (port != i) {
1245						port = -2;
1246						break;
1247					}
1248				}
1249			}
1250		}
1251		err = ch->rslots & cstatus;
1252	} else {
1253		ccs = 0;
1254		err = 0;
1255		port = -1;
1256	}
1257	/* Complete all successfull commands. */
1258	ok = ch->rslots & ~cstatus;
1259	for (i = 0; i < ch->numslots; i++) {
1260		if ((ok >> i) & 1)
1261			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1262	}
1263	/* On error, complete the rest of commands with error statuses. */
1264	if (err) {
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			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1270				xpt_freeze_devq(fccb->ccb_h.path, 1);
1271				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1272			}
1273			ahci_done(ch, fccb);
1274		}
1275		for (i = 0; i < ch->numslots; i++) {
1276			/* XXX: reqests in loading state. */
1277			if (((err >> i) & 1) == 0)
1278				continue;
1279			if (port >= 0 &&
1280			    ch->slot[i].ccb->ccb_h.target_id != port)
1281				continue;
1282			if (istatus & AHCI_P_IX_TFE) {
1283			    if (port != -2) {
1284				/* Task File Error */
1285				if (ch->numtslotspd[
1286				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1287					/* Untagged operation. */
1288					if (i == ccs)
1289						et = AHCI_ERR_TFE;
1290					else
1291						et = AHCI_ERR_INNOCENT;
1292				} else {
1293					/* Tagged operation. */
1294					et = AHCI_ERR_NCQ;
1295				}
1296			    } else {
1297				et = AHCI_ERR_TFE;
1298				ch->fatalerr = 1;
1299			    }
1300			} else if (istatus & AHCI_P_IX_IF) {
1301				if (ch->numtslots == 0 && i != ccs && port != -2)
1302					et = AHCI_ERR_INNOCENT;
1303				else
1304					et = AHCI_ERR_SATA;
1305			} else
1306				et = AHCI_ERR_INVALID;
1307			ahci_end_transaction(&ch->slot[i], et);
1308		}
1309		/*
1310		 * We can't reinit port if there are some other
1311		 * commands active, use resume to complete them.
1312		 */
1313		if (ch->rslots != 0 && !ch->recoverycmd)
1314			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1315	}
1316	/* Process NOTIFY events */
1317	if (sntf)
1318		ahci_notify_events(ch, sntf);
1319}
1320
1321/* Must be called with channel locked. */
1322static int
1323ahci_check_collision(struct ahci_channel *ch, union ccb *ccb)
1324{
1325	int t = ccb->ccb_h.target_id;
1326
1327	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1328	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1329		/* Tagged command while we have no supported tag free. */
1330		if (((~ch->oslots) & (0xffffffff >> (32 -
1331		    ch->curr[t].tags))) == 0)
1332			return (1);
1333		/* If we have FBS */
1334		if (ch->fbs_enabled) {
1335			/* Tagged command while untagged are active. */
1336			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1337				return (1);
1338		} else {
1339			/* Tagged command while untagged are active. */
1340			if (ch->numrslots != 0 && ch->numtslots == 0)
1341				return (1);
1342			/* Tagged command while tagged to other target is active. */
1343			if (ch->numtslots != 0 &&
1344			    ch->taggedtarget != ccb->ccb_h.target_id)
1345				return (1);
1346		}
1347	} else {
1348		/* If we have FBS */
1349		if (ch->fbs_enabled) {
1350			/* Untagged command while tagged are active. */
1351			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1352				return (1);
1353		} else {
1354			/* Untagged command while tagged are active. */
1355			if (ch->numrslots != 0 && ch->numtslots != 0)
1356				return (1);
1357		}
1358	}
1359	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1360	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1361		/* Atomic command while anything active. */
1362		if (ch->numrslots != 0)
1363			return (1);
1364	}
1365       /* We have some atomic command running. */
1366       if (ch->aslots != 0)
1367               return (1);
1368	return (0);
1369}
1370
1371/* Must be called with channel locked. */
1372static void
1373ahci_begin_transaction(struct ahci_channel *ch, union ccb *ccb)
1374{
1375	struct ahci_slot *slot;
1376	int tag, tags;
1377
1378	/* Choose empty slot. */
1379	tags = ch->numslots;
1380	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1381	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1382		tags = ch->curr[ccb->ccb_h.target_id].tags;
1383	if (ch->lastslot + 1 < tags)
1384		tag = ffs(~(ch->oslots >> (ch->lastslot + 1)));
1385	else
1386		tag = 0;
1387	if (tag == 0 || tag + ch->lastslot >= tags)
1388		tag = ffs(~ch->oslots) - 1;
1389	else
1390		tag += ch->lastslot;
1391	ch->lastslot = tag;
1392	/* Occupy chosen slot. */
1393	slot = &ch->slot[tag];
1394	slot->ccb = ccb;
1395	/* Stop PM timer. */
1396	if (ch->numrslots == 0 && ch->pm_level > 3)
1397		callout_stop(&ch->pm_timer);
1398	/* Update channel stats. */
1399	ch->oslots |= (1 << tag);
1400	ch->numrslots++;
1401	ch->numrslotspd[ccb->ccb_h.target_id]++;
1402	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1403	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1404		ch->numtslots++;
1405		ch->numtslotspd[ccb->ccb_h.target_id]++;
1406		ch->taggedtarget = ccb->ccb_h.target_id;
1407	}
1408	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1409	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1410		ch->aslots |= (1 << tag);
1411	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1412		slot->state = AHCI_SLOT_LOADING;
1413		bus_dmamap_load_ccb(ch->dma.data_tag, slot->dma.data_map, ccb,
1414		    ahci_dmasetprd, slot, 0);
1415	} else {
1416		slot->dma.nsegs = 0;
1417		ahci_execute_transaction(slot);
1418	}
1419}
1420
1421/* Locked by busdma engine. */
1422static void
1423ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1424{
1425	struct ahci_slot *slot = arg;
1426	struct ahci_channel *ch = slot->ch;
1427	struct ahci_cmd_tab *ctp;
1428	struct ahci_dma_prd *prd;
1429	int i;
1430
1431	if (error) {
1432		device_printf(ch->dev, "DMA load error\n");
1433		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1434		return;
1435	}
1436	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1437	/* Get a piece of the workspace for this request */
1438	ctp = (struct ahci_cmd_tab *)
1439		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1440	/* Fill S/G table */
1441	prd = &ctp->prd_tab[0];
1442	for (i = 0; i < nsegs; i++) {
1443		prd[i].dba = htole64(segs[i].ds_addr);
1444		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1445	}
1446	slot->dma.nsegs = nsegs;
1447	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1448	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1449	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1450	ahci_execute_transaction(slot);
1451}
1452
1453/* Must be called with channel locked. */
1454static void
1455ahci_execute_transaction(struct ahci_slot *slot)
1456{
1457	struct ahci_channel *ch = slot->ch;
1458	struct ahci_cmd_tab *ctp;
1459	struct ahci_cmd_list *clp;
1460	union ccb *ccb = slot->ccb;
1461	int port = ccb->ccb_h.target_id & 0x0f;
1462	int fis_size, i, softreset;
1463	uint8_t *fis = ch->dma.rfis + 0x40;
1464	uint8_t val;
1465
1466	/* Get a piece of the workspace for this request */
1467	ctp = (struct ahci_cmd_tab *)
1468		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1469	/* Setup the FIS for this request */
1470	if (!(fis_size = ahci_setup_fis(ch, ctp, ccb, slot->slot))) {
1471		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1472		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1473		return;
1474	}
1475	/* Setup the command list entry */
1476	clp = (struct ahci_cmd_list *)
1477	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1478	clp->cmd_flags = htole16(
1479		    (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1480		    (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1481		     (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1482		    (fis_size / sizeof(u_int32_t)) |
1483		    (port << 12));
1484	clp->prd_length = htole16(slot->dma.nsegs);
1485	/* Special handling for Soft Reset command. */
1486	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1487	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1488		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1489			softreset = 1;
1490			/* Kick controller into sane state */
1491			ahci_stop(ch);
1492			ahci_clo(ch);
1493			ahci_start(ch, 0);
1494			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1495		} else {
1496			softreset = 2;
1497			/* Prepare FIS receive area for check. */
1498			for (i = 0; i < 20; i++)
1499				fis[i] = 0xff;
1500		}
1501	} else
1502		softreset = 0;
1503	clp->bytecount = 0;
1504	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1505				  (AHCI_CT_SIZE * slot->slot));
1506	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1507	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1508	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1509	    BUS_DMASYNC_PREREAD);
1510	/* Set ACTIVE bit for NCQ commands. */
1511	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1512	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1513		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1514	}
1515	/* If FBS is enabled, set PMP port. */
1516	if (ch->fbs_enabled) {
1517		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1518		    (port << AHCI_P_FBS_DEV_SHIFT));
1519	}
1520	/* Issue command to the controller. */
1521	slot->state = AHCI_SLOT_RUNNING;
1522	ch->rslots |= (1 << slot->slot);
1523	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1524	/* Device reset commands doesn't interrupt. Poll them. */
1525	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1526	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET || softreset)) {
1527		int count, timeout = ccb->ccb_h.timeout * 100;
1528		enum ahci_err_type et = AHCI_ERR_NONE;
1529
1530		for (count = 0; count < timeout; count++) {
1531			DELAY(10);
1532			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1533				break;
1534			if ((ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) &&
1535			    softreset != 1) {
1536#if 0
1537				device_printf(ch->dev,
1538				    "Poll error on slot %d, TFD: %04x\n",
1539				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1540#endif
1541				et = AHCI_ERR_TFE;
1542				break;
1543			}
1544			/* Workaround for ATI SB600/SB700 chipsets. */
1545			if (ccb->ccb_h.target_id == 15 &&
1546			    (ch->quirks & AHCI_Q_ATI_PMP_BUG) &&
1547			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1548				et = AHCI_ERR_TIMEOUT;
1549				break;
1550			}
1551		}
1552
1553		/*
1554		 * Marvell HBAs with non-RAID firmware do not wait for
1555		 * readiness after soft reset, so we have to wait here.
1556		 * Marvell RAIDs do not have this problem, but instead
1557		 * sometimes forget to update FIS receive area, breaking
1558		 * this wait.
1559		 */
1560		if ((ch->quirks & AHCI_Q_NOBSYRES) == 0 &&
1561		    (ch->quirks & AHCI_Q_ATI_PMP_BUG) == 0 &&
1562		    softreset == 2 && et == AHCI_ERR_NONE) {
1563			while ((val = fis[2]) & ATA_S_BUSY) {
1564				DELAY(10);
1565				if (count++ >= timeout)
1566					break;
1567			}
1568		}
1569
1570		if (timeout && (count >= timeout)) {
1571			device_printf(ch->dev, "Poll timeout on slot %d port %d\n",
1572			    slot->slot, port);
1573			device_printf(ch->dev, "is %08x cs %08x ss %08x "
1574			    "rs %08x tfd %02x serr %08x cmd %08x\n",
1575			    ATA_INL(ch->r_mem, AHCI_P_IS),
1576			    ATA_INL(ch->r_mem, AHCI_P_CI),
1577			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1578			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1579			    ATA_INL(ch->r_mem, AHCI_P_SERR),
1580			    ATA_INL(ch->r_mem, AHCI_P_CMD));
1581			et = AHCI_ERR_TIMEOUT;
1582		}
1583
1584		/* Kick controller into sane state and enable FBS. */
1585		if (softreset == 2)
1586			ch->eslots |= (1 << slot->slot);
1587		ahci_end_transaction(slot, et);
1588		return;
1589	}
1590	/* Start command execution timeout */
1591	callout_reset_sbt(&slot->timeout, SBT_1MS * ccb->ccb_h.timeout / 2,
1592	    0, (timeout_t*)ahci_timeout, slot, 0);
1593	return;
1594}
1595
1596/* Must be called with channel locked. */
1597static void
1598ahci_process_timeout(struct ahci_channel *ch)
1599{
1600	int i;
1601
1602	mtx_assert(&ch->mtx, MA_OWNED);
1603	/* Handle the rest of commands. */
1604	for (i = 0; i < ch->numslots; i++) {
1605		/* Do we have a running request on slot? */
1606		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1607			continue;
1608		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1609	}
1610}
1611
1612/* Must be called with channel locked. */
1613static void
1614ahci_rearm_timeout(struct ahci_channel *ch)
1615{
1616	int i;
1617
1618	mtx_assert(&ch->mtx, MA_OWNED);
1619	for (i = 0; i < ch->numslots; i++) {
1620		struct ahci_slot *slot = &ch->slot[i];
1621
1622		/* Do we have a running request on slot? */
1623		if (slot->state < AHCI_SLOT_RUNNING)
1624			continue;
1625		if ((ch->toslots & (1 << i)) == 0)
1626			continue;
1627		callout_reset_sbt(&slot->timeout,
1628    	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1629		    (timeout_t*)ahci_timeout, slot, 0);
1630	}
1631}
1632
1633/* Locked by callout mechanism. */
1634static void
1635ahci_timeout(struct ahci_slot *slot)
1636{
1637	struct ahci_channel *ch = slot->ch;
1638	device_t dev = ch->dev;
1639	uint32_t sstatus;
1640	int ccs;
1641	int i;
1642
1643	/* Check for stale timeout. */
1644	if (slot->state < AHCI_SLOT_RUNNING)
1645		return;
1646
1647	/* Check if slot was not being executed last time we checked. */
1648	if (slot->state < AHCI_SLOT_EXECUTING) {
1649		/* Check if slot started executing. */
1650		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1651		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1652		    >> AHCI_P_CMD_CCS_SHIFT;
1653		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1654		    ch->fbs_enabled || ch->wrongccs)
1655			slot->state = AHCI_SLOT_EXECUTING;
1656		else if ((ch->rslots & (1 << ccs)) == 0) {
1657			ch->wrongccs = 1;
1658			slot->state = AHCI_SLOT_EXECUTING;
1659		}
1660
1661		callout_reset_sbt(&slot->timeout,
1662	    	    SBT_1MS * slot->ccb->ccb_h.timeout / 2, 0,
1663		    (timeout_t*)ahci_timeout, slot, 0);
1664		return;
1665	}
1666
1667	device_printf(dev, "Timeout on slot %d port %d\n",
1668	    slot->slot, slot->ccb->ccb_h.target_id & 0x0f);
1669	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x "
1670	    "serr %08x cmd %08x\n",
1671	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1672	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1673	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR),
1674	    ATA_INL(ch->r_mem, AHCI_P_CMD));
1675
1676	/* Handle frozen command. */
1677	if (ch->frozen) {
1678		union ccb *fccb = ch->frozen;
1679		ch->frozen = NULL;
1680		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1681		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1682			xpt_freeze_devq(fccb->ccb_h.path, 1);
1683			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1684		}
1685		ahci_done(ch, fccb);
1686	}
1687	if (!ch->fbs_enabled && !ch->wrongccs) {
1688		/* Without FBS we know real timeout source. */
1689		ch->fatalerr = 1;
1690		/* Handle command with timeout. */
1691		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1692		/* Handle the rest of commands. */
1693		for (i = 0; i < ch->numslots; i++) {
1694			/* Do we have a running request on slot? */
1695			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1696				continue;
1697			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1698		}
1699	} else {
1700		/* With FBS we wait for other commands timeout and pray. */
1701		if (ch->toslots == 0)
1702			xpt_freeze_simq(ch->sim, 1);
1703		ch->toslots |= (1 << slot->slot);
1704		if ((ch->rslots & ~ch->toslots) == 0)
1705			ahci_process_timeout(ch);
1706		else
1707			device_printf(dev, " ... waiting for slots %08x\n",
1708			    ch->rslots & ~ch->toslots);
1709	}
1710}
1711
1712/* Must be called with channel locked. */
1713static void
1714ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1715{
1716	struct ahci_channel *ch = slot->ch;
1717	union ccb *ccb = slot->ccb;
1718	struct ahci_cmd_list *clp;
1719	int lastto;
1720	uint32_t sig;
1721
1722	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1723	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1724	clp = (struct ahci_cmd_list *)
1725	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1726	/* Read result registers to the result struct
1727	 * May be incorrect if several commands finished same time,
1728	 * so read only when sure or have to.
1729	 */
1730	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1731		struct ata_res *res = &ccb->ataio.res;
1732
1733		if ((et == AHCI_ERR_TFE) ||
1734		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1735			u_int8_t *fis = ch->dma.rfis + 0x40;
1736
1737			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1738			    BUS_DMASYNC_POSTREAD);
1739			if (ch->fbs_enabled) {
1740				fis += ccb->ccb_h.target_id * 256;
1741				res->status = fis[2];
1742				res->error = fis[3];
1743			} else {
1744				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1745
1746				res->status = tfd;
1747				res->error = tfd >> 8;
1748			}
1749			res->lba_low = fis[4];
1750			res->lba_mid = fis[5];
1751			res->lba_high = fis[6];
1752			res->device = fis[7];
1753			res->lba_low_exp = fis[8];
1754			res->lba_mid_exp = fis[9];
1755			res->lba_high_exp = fis[10];
1756			res->sector_count = fis[12];
1757			res->sector_count_exp = fis[13];
1758
1759			/*
1760			 * Some weird controllers do not return signature in
1761			 * FIS receive area. Read it from PxSIG register.
1762			 */
1763			if ((ch->quirks & AHCI_Q_ALTSIG) &&
1764			    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1765			    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1766				sig = ATA_INL(ch->r_mem,  AHCI_P_SIG);
1767				res->lba_high = sig >> 24;
1768				res->lba_mid = sig >> 16;
1769				res->lba_low = sig >> 8;
1770				res->sector_count = sig;
1771			}
1772		} else
1773			bzero(res, sizeof(*res));
1774		if ((ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) == 0 &&
1775		    (ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1776		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
1777			ccb->ataio.resid =
1778			    ccb->ataio.dxfer_len - le32toh(clp->bytecount);
1779		}
1780	} else {
1781		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1782		    (ch->quirks & AHCI_Q_NOCOUNT) == 0) {
1783			ccb->csio.resid =
1784			    ccb->csio.dxfer_len - le32toh(clp->bytecount);
1785		}
1786	}
1787	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1788		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1789		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1790		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1791		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1792	}
1793	if (et != AHCI_ERR_NONE)
1794		ch->eslots |= (1 << slot->slot);
1795	/* In case of error, freeze device for proper recovery. */
1796	if ((et != AHCI_ERR_NONE) && (!ch->recoverycmd) &&
1797	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1798		xpt_freeze_devq(ccb->ccb_h.path, 1);
1799		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1800	}
1801	/* Set proper result status. */
1802	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1803	switch (et) {
1804	case AHCI_ERR_NONE:
1805		ccb->ccb_h.status |= CAM_REQ_CMP;
1806		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1807			ccb->csio.scsi_status = SCSI_STATUS_OK;
1808		break;
1809	case AHCI_ERR_INVALID:
1810		ch->fatalerr = 1;
1811		ccb->ccb_h.status |= CAM_REQ_INVALID;
1812		break;
1813	case AHCI_ERR_INNOCENT:
1814		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1815		break;
1816	case AHCI_ERR_TFE:
1817	case AHCI_ERR_NCQ:
1818		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1819			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1820			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1821		} else {
1822			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1823		}
1824		break;
1825	case AHCI_ERR_SATA:
1826		ch->fatalerr = 1;
1827		if (!ch->recoverycmd) {
1828			xpt_freeze_simq(ch->sim, 1);
1829			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1830			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1831		}
1832		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1833		break;
1834	case AHCI_ERR_TIMEOUT:
1835		if (!ch->recoverycmd) {
1836			xpt_freeze_simq(ch->sim, 1);
1837			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1838			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1839		}
1840		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1841		break;
1842	default:
1843		ch->fatalerr = 1;
1844		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1845	}
1846	/* Free slot. */
1847	ch->oslots &= ~(1 << slot->slot);
1848	ch->rslots &= ~(1 << slot->slot);
1849	ch->aslots &= ~(1 << slot->slot);
1850	slot->state = AHCI_SLOT_EMPTY;
1851	slot->ccb = NULL;
1852	/* Update channel stats. */
1853	ch->numrslots--;
1854	ch->numrslotspd[ccb->ccb_h.target_id]--;
1855	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1856	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1857		ch->numtslots--;
1858		ch->numtslotspd[ccb->ccb_h.target_id]--;
1859	}
1860	/* Cancel timeout state if request completed normally. */
1861	if (et != AHCI_ERR_TIMEOUT) {
1862		lastto = (ch->toslots == (1 << slot->slot));
1863		ch->toslots &= ~(1 << slot->slot);
1864		if (lastto)
1865			xpt_release_simq(ch->sim, TRUE);
1866	}
1867	/* If it was first request of reset sequence and there is no error,
1868	 * proceed to second request. */
1869	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1870	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1871	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1872	    et == AHCI_ERR_NONE) {
1873		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1874		ahci_begin_transaction(ch, ccb);
1875		return;
1876	}
1877	/* If it was our READ LOG command - process it. */
1878	if (ccb->ccb_h.recovery_type == RECOVERY_READ_LOG) {
1879		ahci_process_read_log(ch, ccb);
1880	/* If it was our REQUEST SENSE command - process it. */
1881	} else if (ccb->ccb_h.recovery_type == RECOVERY_REQUEST_SENSE) {
1882		ahci_process_request_sense(ch, ccb);
1883	/* If it was NCQ or ATAPI command error, put result on hold. */
1884	} else if (et == AHCI_ERR_NCQ ||
1885	    ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR &&
1886	     (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)) {
1887		ch->hold[slot->slot] = ccb;
1888		ch->numhslots++;
1889	} else
1890		ahci_done(ch, ccb);
1891	/* If we have no other active commands, ... */
1892	if (ch->rslots == 0) {
1893		/* if there was fatal error - reset port. */
1894		if (ch->toslots != 0 || ch->fatalerr) {
1895			ahci_reset(ch);
1896		} else {
1897			/* if we have slots in error, we can reinit port. */
1898			if (ch->eslots != 0) {
1899				ahci_stop(ch);
1900				ahci_clo(ch);
1901				ahci_start(ch, 1);
1902			}
1903			/* if there commands on hold, we can do READ LOG. */
1904			if (!ch->recoverycmd && ch->numhslots)
1905				ahci_issue_recovery(ch);
1906		}
1907	/* If all the rest of commands are in timeout - give them chance. */
1908	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1909	    et != AHCI_ERR_TIMEOUT)
1910		ahci_rearm_timeout(ch);
1911	/* Unfreeze frozen command. */
1912	if (ch->frozen && !ahci_check_collision(ch, ch->frozen)) {
1913		union ccb *fccb = ch->frozen;
1914		ch->frozen = NULL;
1915		ahci_begin_transaction(ch, fccb);
1916		xpt_release_simq(ch->sim, TRUE);
1917	}
1918	/* Start PM timer. */
1919	if (ch->numrslots == 0 && ch->pm_level > 3 &&
1920	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
1921		callout_schedule(&ch->pm_timer,
1922		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1923	}
1924}
1925
1926static void
1927ahci_issue_recovery(struct ahci_channel *ch)
1928{
1929	union ccb *ccb;
1930	struct ccb_ataio *ataio;
1931	struct ccb_scsiio *csio;
1932	int i;
1933
1934	/* Find some held command. */
1935	for (i = 0; i < ch->numslots; i++) {
1936		if (ch->hold[i])
1937			break;
1938	}
1939	ccb = xpt_alloc_ccb_nowait();
1940	if (ccb == NULL) {
1941		device_printf(ch->dev, "Unable to allocate recovery command\n");
1942completeall:
1943		/* We can't do anything -- complete held commands. */
1944		for (i = 0; i < ch->numslots; i++) {
1945			if (ch->hold[i] == NULL)
1946				continue;
1947			ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1948			ch->hold[i]->ccb_h.status |= CAM_RESRC_UNAVAIL;
1949			ahci_done(ch, ch->hold[i]);
1950			ch->hold[i] = NULL;
1951			ch->numhslots--;
1952		}
1953		ahci_reset(ch);
1954		return;
1955	}
1956	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1957	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1958		/* READ LOG */
1959		ccb->ccb_h.recovery_type = RECOVERY_READ_LOG;
1960		ccb->ccb_h.func_code = XPT_ATA_IO;
1961		ccb->ccb_h.flags = CAM_DIR_IN;
1962		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1963		ataio = &ccb->ataio;
1964		ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1965		if (ataio->data_ptr == NULL) {
1966			xpt_free_ccb(ccb);
1967			device_printf(ch->dev,
1968			    "Unable to allocate memory for READ LOG command\n");
1969			goto completeall;
1970		}
1971		ataio->dxfer_len = 512;
1972		bzero(&ataio->cmd, sizeof(ataio->cmd));
1973		ataio->cmd.flags = CAM_ATAIO_48BIT;
1974		ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1975		ataio->cmd.sector_count = 1;
1976		ataio->cmd.sector_count_exp = 0;
1977		ataio->cmd.lba_low = 0x10;
1978		ataio->cmd.lba_mid = 0;
1979		ataio->cmd.lba_mid_exp = 0;
1980	} else {
1981		/* REQUEST SENSE */
1982		ccb->ccb_h.recovery_type = RECOVERY_REQUEST_SENSE;
1983		ccb->ccb_h.recovery_slot = i;
1984		ccb->ccb_h.func_code = XPT_SCSI_IO;
1985		ccb->ccb_h.flags = CAM_DIR_IN;
1986		ccb->ccb_h.status = 0;
1987		ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1988		csio = &ccb->csio;
1989		csio->data_ptr = (void *)&ch->hold[i]->csio.sense_data;
1990		csio->dxfer_len = ch->hold[i]->csio.sense_len;
1991		csio->cdb_len = 6;
1992		bzero(&csio->cdb_io, sizeof(csio->cdb_io));
1993		csio->cdb_io.cdb_bytes[0] = 0x03;
1994		csio->cdb_io.cdb_bytes[4] = csio->dxfer_len;
1995	}
1996	/* Freeze SIM while doing recovery. */
1997	ch->recoverycmd = 1;
1998	xpt_freeze_simq(ch->sim, 1);
1999	ahci_begin_transaction(ch, ccb);
2000}
2001
2002static void
2003ahci_process_read_log(struct ahci_channel *ch, union ccb *ccb)
2004{
2005	uint8_t *data;
2006	struct ata_res *res;
2007	int i;
2008
2009	ch->recoverycmd = 0;
2010
2011	data = ccb->ataio.data_ptr;
2012	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2013	    (data[0] & 0x80) == 0) {
2014		for (i = 0; i < ch->numslots; i++) {
2015			if (!ch->hold[i])
2016				continue;
2017			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2018				continue;
2019			if ((data[0] & 0x1F) == i) {
2020				res = &ch->hold[i]->ataio.res;
2021				res->status = data[2];
2022				res->error = data[3];
2023				res->lba_low = data[4];
2024				res->lba_mid = data[5];
2025				res->lba_high = data[6];
2026				res->device = data[7];
2027				res->lba_low_exp = data[8];
2028				res->lba_mid_exp = data[9];
2029				res->lba_high_exp = data[10];
2030				res->sector_count = data[12];
2031				res->sector_count_exp = data[13];
2032			} else {
2033				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2034				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2035			}
2036			ahci_done(ch, ch->hold[i]);
2037			ch->hold[i] = NULL;
2038			ch->numhslots--;
2039		}
2040	} else {
2041		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2042			device_printf(ch->dev, "Error while READ LOG EXT\n");
2043		else if ((data[0] & 0x80) == 0) {
2044			device_printf(ch->dev, "Non-queued command error in READ LOG EXT\n");
2045		}
2046		for (i = 0; i < ch->numslots; i++) {
2047			if (!ch->hold[i])
2048				continue;
2049			if (ch->hold[i]->ccb_h.func_code != XPT_ATA_IO)
2050				continue;
2051			ahci_done(ch, ch->hold[i]);
2052			ch->hold[i] = NULL;
2053			ch->numhslots--;
2054		}
2055	}
2056	free(ccb->ataio.data_ptr, M_AHCI);
2057	xpt_free_ccb(ccb);
2058	xpt_release_simq(ch->sim, TRUE);
2059}
2060
2061static void
2062ahci_process_request_sense(struct ahci_channel *ch, union ccb *ccb)
2063{
2064	int i;
2065
2066	ch->recoverycmd = 0;
2067
2068	i = ccb->ccb_h.recovery_slot;
2069	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2070		ch->hold[i]->ccb_h.status |= CAM_AUTOSNS_VALID;
2071	} else {
2072		ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2073		ch->hold[i]->ccb_h.status |= CAM_AUTOSENSE_FAIL;
2074	}
2075	ahci_done(ch, ch->hold[i]);
2076	ch->hold[i] = NULL;
2077	ch->numhslots--;
2078	xpt_free_ccb(ccb);
2079	xpt_release_simq(ch->sim, TRUE);
2080}
2081
2082static void
2083ahci_start(struct ahci_channel *ch, int fbs)
2084{
2085	u_int32_t cmd;
2086
2087	/* Clear SATA error register */
2088	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2089	/* Clear any interrupts pending on this channel */
2090	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2091	/* Configure FIS-based switching if supported. */
2092	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2093		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2094		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2095		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2096	}
2097	/* Start operations on this channel */
2098	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2099	cmd &= ~AHCI_P_CMD_PMA;
2100	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2101	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2102}
2103
2104static void
2105ahci_stop(struct ahci_channel *ch)
2106{
2107	u_int32_t cmd;
2108	int timeout;
2109
2110	/* Kill all activity on this channel */
2111	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2112	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2113	/* Wait for activity stop. */
2114	timeout = 0;
2115	do {
2116		DELAY(10);
2117		if (timeout++ > 50000) {
2118			device_printf(ch->dev, "stopping AHCI engine failed\n");
2119			break;
2120		}
2121	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2122	ch->eslots = 0;
2123}
2124
2125static void
2126ahci_clo(struct ahci_channel *ch)
2127{
2128	u_int32_t cmd;
2129	int timeout;
2130
2131	/* Issue Command List Override if supported */
2132	if (ch->caps & AHCI_CAP_SCLO) {
2133		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2134		cmd |= AHCI_P_CMD_CLO;
2135		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2136		timeout = 0;
2137		do {
2138			DELAY(10);
2139			if (timeout++ > 50000) {
2140			    device_printf(ch->dev, "executing CLO failed\n");
2141			    break;
2142			}
2143		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2144	}
2145}
2146
2147static void
2148ahci_stop_fr(struct ahci_channel *ch)
2149{
2150	u_int32_t cmd;
2151	int timeout;
2152
2153	/* Kill all FIS reception on this channel */
2154	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2155	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2156	/* Wait for FIS reception stop. */
2157	timeout = 0;
2158	do {
2159		DELAY(10);
2160		if (timeout++ > 50000) {
2161			device_printf(ch->dev, "stopping AHCI FR engine failed\n");
2162			break;
2163		}
2164	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2165}
2166
2167static void
2168ahci_start_fr(struct ahci_channel *ch)
2169{
2170	u_int32_t cmd;
2171
2172	/* Start FIS reception on this channel */
2173	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2174	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2175}
2176
2177static int
2178ahci_wait_ready(struct ahci_channel *ch, int t, int t0)
2179{
2180	int timeout = 0;
2181	uint32_t val;
2182
2183	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2184	    (ATA_S_BUSY | ATA_S_DRQ)) {
2185		if (timeout > t) {
2186			if (t != 0) {
2187				device_printf(ch->dev,
2188				    "AHCI reset: device not ready after %dms "
2189				    "(tfd = %08x)\n",
2190				    MAX(t, 0) + t0, val);
2191			}
2192			return (EBUSY);
2193		}
2194		DELAY(1000);
2195		timeout++;
2196	}
2197	if (bootverbose)
2198		device_printf(ch->dev, "AHCI reset: device ready after %dms\n",
2199		    timeout + t0);
2200	return (0);
2201}
2202
2203static void
2204ahci_reset_to(void *arg)
2205{
2206	struct ahci_channel *ch = arg;
2207
2208	if (ch->resetting == 0)
2209		return;
2210	ch->resetting--;
2211	if (ahci_wait_ready(ch, ch->resetting == 0 ? -1 : 0,
2212	    (310 - ch->resetting) * 100) == 0) {
2213		ch->resetting = 0;
2214		ahci_start(ch, 1);
2215		xpt_release_simq(ch->sim, TRUE);
2216		return;
2217	}
2218	if (ch->resetting == 0) {
2219		ahci_clo(ch);
2220		ahci_start(ch, 1);
2221		xpt_release_simq(ch->sim, TRUE);
2222		return;
2223	}
2224	callout_schedule(&ch->reset_timer, hz / 10);
2225}
2226
2227static void
2228ahci_reset(struct ahci_channel *ch)
2229{
2230	struct ahci_controller *ctlr = device_get_softc(device_get_parent(ch->dev));
2231	int i;
2232
2233	xpt_freeze_simq(ch->sim, 1);
2234	if (bootverbose)
2235		device_printf(ch->dev, "AHCI reset...\n");
2236	/* Forget about previous reset. */
2237	if (ch->resetting) {
2238		ch->resetting = 0;
2239		callout_stop(&ch->reset_timer);
2240		xpt_release_simq(ch->sim, TRUE);
2241	}
2242	/* Requeue freezed command. */
2243	if (ch->frozen) {
2244		union ccb *fccb = ch->frozen;
2245		ch->frozen = NULL;
2246		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2247		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2248			xpt_freeze_devq(fccb->ccb_h.path, 1);
2249			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2250		}
2251		ahci_done(ch, fccb);
2252	}
2253	/* Kill the engine and requeue all running commands. */
2254	ahci_stop(ch);
2255	for (i = 0; i < ch->numslots; i++) {
2256		/* Do we have a running request on slot? */
2257		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2258			continue;
2259		/* XXX; Commands in loading state. */
2260		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2261	}
2262	for (i = 0; i < ch->numslots; i++) {
2263		if (!ch->hold[i])
2264			continue;
2265		ahci_done(ch, ch->hold[i]);
2266		ch->hold[i] = NULL;
2267		ch->numhslots--;
2268	}
2269	if (ch->toslots != 0)
2270		xpt_release_simq(ch->sim, TRUE);
2271	ch->eslots = 0;
2272	ch->toslots = 0;
2273	ch->wrongccs = 0;
2274	ch->fatalerr = 0;
2275	/* Tell the XPT about the event */
2276	xpt_async(AC_BUS_RESET, ch->path, NULL);
2277	/* Disable port interrupts */
2278	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2279	/* Reset and reconnect PHY, */
2280	if (!ahci_sata_phy_reset(ch)) {
2281		if (bootverbose)
2282			device_printf(ch->dev,
2283			    "AHCI reset: device not found\n");
2284		ch->devices = 0;
2285		/* Enable wanted port interrupts */
2286		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2287		    (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2288		     AHCI_P_IX_PRC | AHCI_P_IX_PC));
2289		xpt_release_simq(ch->sim, TRUE);
2290		return;
2291	}
2292	if (bootverbose)
2293		device_printf(ch->dev, "AHCI reset: device found\n");
2294	/* Wait for clearing busy status. */
2295	if (ahci_wait_ready(ch, dumping ? 31000 : 0, 0)) {
2296		if (dumping)
2297			ahci_clo(ch);
2298		else
2299			ch->resetting = 310;
2300	}
2301	ch->devices = 1;
2302	/* Enable wanted port interrupts */
2303	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2304	     (((ch->pm_level != 0) ? AHCI_P_IX_CPD | AHCI_P_IX_MP : 0) |
2305	      AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2306	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2307	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC : 0) | AHCI_P_IX_PC |
2308	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2309	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2310	if (ch->resetting)
2311		callout_reset(&ch->reset_timer, hz / 10, ahci_reset_to, ch);
2312	else {
2313		ahci_start(ch, 1);
2314		xpt_release_simq(ch->sim, TRUE);
2315	}
2316}
2317
2318static int
2319ahci_setup_fis(struct ahci_channel *ch, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2320{
2321	u_int8_t *fis = &ctp->cfis[0];
2322
2323	bzero(fis, 20);
2324	fis[0] = 0x27;  		/* host to device */
2325	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2326	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2327		fis[1] |= 0x80;
2328		fis[2] = ATA_PACKET_CMD;
2329		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2330		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2331			fis[3] = ATA_F_DMA;
2332		else {
2333			fis[5] = ccb->csio.dxfer_len;
2334		        fis[6] = ccb->csio.dxfer_len >> 8;
2335		}
2336		fis[7] = ATA_D_LBA;
2337		fis[15] = ATA_A_4BIT;
2338		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2339		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2340		    ctp->acmd, ccb->csio.cdb_len);
2341		bzero(ctp->acmd + ccb->csio.cdb_len, 32 - ccb->csio.cdb_len);
2342	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2343		fis[1] |= 0x80;
2344		fis[2] = ccb->ataio.cmd.command;
2345		fis[3] = ccb->ataio.cmd.features;
2346		fis[4] = ccb->ataio.cmd.lba_low;
2347		fis[5] = ccb->ataio.cmd.lba_mid;
2348		fis[6] = ccb->ataio.cmd.lba_high;
2349		fis[7] = ccb->ataio.cmd.device;
2350		fis[8] = ccb->ataio.cmd.lba_low_exp;
2351		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2352		fis[10] = ccb->ataio.cmd.lba_high_exp;
2353		fis[11] = ccb->ataio.cmd.features_exp;
2354		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2355			fis[12] = tag << 3;
2356			fis[13] = 0;
2357		} else {
2358			fis[12] = ccb->ataio.cmd.sector_count;
2359			fis[13] = ccb->ataio.cmd.sector_count_exp;
2360		}
2361		fis[15] = ATA_A_4BIT;
2362	} else {
2363		fis[15] = ccb->ataio.cmd.control;
2364	}
2365	return (20);
2366}
2367
2368static int
2369ahci_sata_connect(struct ahci_channel *ch)
2370{
2371	u_int32_t status;
2372	int timeout, found = 0;
2373
2374	/* Wait up to 100ms for "connect well" */
2375	for (timeout = 0; timeout < 1000 ; timeout++) {
2376		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2377		if ((status & ATA_SS_DET_MASK) != ATA_SS_DET_NO_DEVICE)
2378			found = 1;
2379		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2380		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2381		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2382			break;
2383		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2384			if (bootverbose) {
2385				device_printf(ch->dev, "SATA offline status=%08x\n",
2386				    status);
2387			}
2388			return (0);
2389		}
2390		if (found == 0 && timeout >= 100)
2391			break;
2392		DELAY(100);
2393	}
2394	if (timeout >= 1000 || !found) {
2395		if (bootverbose) {
2396			device_printf(ch->dev,
2397			    "SATA connect timeout time=%dus status=%08x\n",
2398			    timeout * 100, status);
2399		}
2400		return (0);
2401	}
2402	if (bootverbose) {
2403		device_printf(ch->dev, "SATA connect time=%dus status=%08x\n",
2404		    timeout * 100, status);
2405	}
2406	/* Clear SATA error register */
2407	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2408	return (1);
2409}
2410
2411static int
2412ahci_sata_phy_reset(struct ahci_channel *ch)
2413{
2414	int sata_rev;
2415	uint32_t val;
2416
2417	if (ch->listening) {
2418		val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2419		val |= AHCI_P_CMD_SUD;
2420		ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2421		ch->listening = 0;
2422	}
2423	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2424	if (sata_rev == 1)
2425		val = ATA_SC_SPD_SPEED_GEN1;
2426	else if (sata_rev == 2)
2427		val = ATA_SC_SPD_SPEED_GEN2;
2428	else if (sata_rev == 3)
2429		val = ATA_SC_SPD_SPEED_GEN3;
2430	else
2431		val = 0;
2432	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2433	    ATA_SC_DET_RESET | val |
2434	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2435	DELAY(1000);
2436	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2437	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2438	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2439	if (!ahci_sata_connect(ch)) {
2440		if (ch->caps & AHCI_CAP_SSS) {
2441			val = ATA_INL(ch->r_mem, AHCI_P_CMD);
2442			val &= ~AHCI_P_CMD_SUD;
2443			ATA_OUTL(ch->r_mem, AHCI_P_CMD, val);
2444			ch->listening = 1;
2445		} else if (ch->pm_level > 0)
2446			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2447		return (0);
2448	}
2449	return (1);
2450}
2451
2452static int
2453ahci_check_ids(struct ahci_channel *ch, union ccb *ccb)
2454{
2455
2456	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2457		ccb->ccb_h.status = CAM_TID_INVALID;
2458		ahci_done(ch, ccb);
2459		return (-1);
2460	}
2461	if (ccb->ccb_h.target_lun != 0) {
2462		ccb->ccb_h.status = CAM_LUN_INVALID;
2463		ahci_done(ch, ccb);
2464		return (-1);
2465	}
2466	return (0);
2467}
2468
2469static void
2470ahciaction(struct cam_sim *sim, union ccb *ccb)
2471{
2472	struct ahci_channel *ch;
2473
2474	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2475	    ccb->ccb_h.func_code));
2476
2477	ch = (struct ahci_channel *)cam_sim_softc(sim);
2478	switch (ccb->ccb_h.func_code) {
2479	/* Common cases first */
2480	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2481	case XPT_SCSI_IO:
2482		if (ahci_check_ids(ch, ccb))
2483			return;
2484		if (ch->devices == 0 ||
2485		    (ch->pm_present == 0 &&
2486		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2487			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2488			break;
2489		}
2490		ccb->ccb_h.recovery_type = RECOVERY_NONE;
2491		/* Check for command collision. */
2492		if (ahci_check_collision(ch, ccb)) {
2493			/* Freeze command. */
2494			ch->frozen = ccb;
2495			/* We have only one frozen slot, so freeze simq also. */
2496			xpt_freeze_simq(ch->sim, 1);
2497			return;
2498		}
2499		ahci_begin_transaction(ch, ccb);
2500		return;
2501	case XPT_EN_LUN:		/* Enable LUN as a target */
2502	case XPT_TARGET_IO:		/* Execute target I/O request */
2503	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2504	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2505	case XPT_ABORT:			/* Abort the specified CCB */
2506		/* XXX Implement */
2507		ccb->ccb_h.status = CAM_REQ_INVALID;
2508		break;
2509	case XPT_SET_TRAN_SETTINGS:
2510	{
2511		struct	ccb_trans_settings *cts = &ccb->cts;
2512		struct	ahci_device *d;
2513
2514		if (ahci_check_ids(ch, ccb))
2515			return;
2516		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2517			d = &ch->curr[ccb->ccb_h.target_id];
2518		else
2519			d = &ch->user[ccb->ccb_h.target_id];
2520		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2521			d->revision = cts->xport_specific.sata.revision;
2522		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2523			d->mode = cts->xport_specific.sata.mode;
2524		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2525			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2526		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2527			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2528		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2529			ch->pm_present = cts->xport_specific.sata.pm_present;
2530		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2531			d->atapi = cts->xport_specific.sata.atapi;
2532		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2533			d->caps = cts->xport_specific.sata.caps;
2534		ccb->ccb_h.status = CAM_REQ_CMP;
2535		break;
2536	}
2537	case XPT_GET_TRAN_SETTINGS:
2538	/* Get default/user set transfer settings for the target */
2539	{
2540		struct	ccb_trans_settings *cts = &ccb->cts;
2541		struct  ahci_device *d;
2542		uint32_t status;
2543
2544		if (ahci_check_ids(ch, ccb))
2545			return;
2546		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2547			d = &ch->curr[ccb->ccb_h.target_id];
2548		else
2549			d = &ch->user[ccb->ccb_h.target_id];
2550		cts->protocol = PROTO_UNSPECIFIED;
2551		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2552		cts->transport = XPORT_SATA;
2553		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2554		cts->proto_specific.valid = 0;
2555		cts->xport_specific.sata.valid = 0;
2556		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2557		    (ccb->ccb_h.target_id == 15 ||
2558		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2559			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2560			if (status & 0x0f0) {
2561				cts->xport_specific.sata.revision =
2562				    (status & 0x0f0) >> 4;
2563				cts->xport_specific.sata.valid |=
2564				    CTS_SATA_VALID_REVISION;
2565			}
2566			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2567			if (ch->pm_level) {
2568				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2569					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2570				if (ch->caps2 & AHCI_CAP2_APST)
2571					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2572			}
2573			if ((ch->caps & AHCI_CAP_SNCQ) &&
2574			    (ch->quirks & AHCI_Q_NOAA) == 0)
2575				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2576			cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_AN;
2577			cts->xport_specific.sata.caps &=
2578			    ch->user[ccb->ccb_h.target_id].caps;
2579			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2580		} else {
2581			cts->xport_specific.sata.revision = d->revision;
2582			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2583			cts->xport_specific.sata.caps = d->caps;
2584			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2585		}
2586		cts->xport_specific.sata.mode = d->mode;
2587		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2588		cts->xport_specific.sata.bytecount = d->bytecount;
2589		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2590		cts->xport_specific.sata.pm_present = ch->pm_present;
2591		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2592		cts->xport_specific.sata.tags = d->tags;
2593		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2594		cts->xport_specific.sata.atapi = d->atapi;
2595		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2596		ccb->ccb_h.status = CAM_REQ_CMP;
2597		break;
2598	}
2599	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2600	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2601		ahci_reset(ch);
2602		ccb->ccb_h.status = CAM_REQ_CMP;
2603		break;
2604	case XPT_TERM_IO:		/* Terminate the I/O process */
2605		/* XXX Implement */
2606		ccb->ccb_h.status = CAM_REQ_INVALID;
2607		break;
2608	case XPT_PATH_INQ:		/* Path routing inquiry */
2609	{
2610		struct ccb_pathinq *cpi = &ccb->cpi;
2611
2612		cpi->version_num = 1; /* XXX??? */
2613		cpi->hba_inquiry = PI_SDTR_ABLE;
2614		if (ch->caps & AHCI_CAP_SNCQ)
2615			cpi->hba_inquiry |= PI_TAG_ABLE;
2616		if (ch->caps & AHCI_CAP_SPM)
2617			cpi->hba_inquiry |= PI_SATAPM;
2618		cpi->target_sprt = 0;
2619		cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED;
2620		cpi->hba_eng_cnt = 0;
2621		if (ch->caps & AHCI_CAP_SPM)
2622			cpi->max_target = 15;
2623		else
2624			cpi->max_target = 0;
2625		cpi->max_lun = 0;
2626		cpi->initiator_id = 0;
2627		cpi->bus_id = cam_sim_bus(sim);
2628		cpi->base_transfer_speed = 150000;
2629		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2630		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2631		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2632		cpi->unit_number = cam_sim_unit(sim);
2633		cpi->transport = XPORT_SATA;
2634		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2635		cpi->protocol = PROTO_ATA;
2636		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2637		cpi->maxio = MAXPHYS;
2638		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2639		if (ch->quirks & AHCI_Q_MAXIO_64K)
2640			cpi->maxio = min(cpi->maxio, 128 * 512);
2641		cpi->hba_vendor = ch->vendorid;
2642		cpi->hba_device = ch->deviceid;
2643		cpi->hba_subvendor = ch->subvendorid;
2644		cpi->hba_subdevice = ch->subdeviceid;
2645		cpi->ccb_h.status = CAM_REQ_CMP;
2646		break;
2647	}
2648	default:
2649		ccb->ccb_h.status = CAM_REQ_INVALID;
2650		break;
2651	}
2652	ahci_done(ch, ccb);
2653}
2654
2655static void
2656ahcipoll(struct cam_sim *sim)
2657{
2658	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2659	uint32_t istatus;
2660
2661	/* Read interrupt statuses and process if any. */
2662	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
2663	if (istatus != 0)
2664		ahci_ch_intr_main(ch, istatus);
2665	if (ch->resetting != 0 &&
2666	    (--ch->resetpolldiv <= 0 || !callout_pending(&ch->reset_timer))) {
2667		ch->resetpolldiv = 1000;
2668		ahci_reset_to(ch);
2669	}
2670}
2671MODULE_VERSION(ahci, 1);
2672MODULE_DEPEND(ahci, cam, 1, 1, 1);
2673