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