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