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