ahci_generic.c revision 208375
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 208375 2010-05-21 13:29:28Z 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
781devclass_t ahci_devclass;
782static device_method_t ahci_methods[] = {
783	DEVMETHOD(device_probe,     ahci_probe),
784	DEVMETHOD(device_attach,    ahci_attach),
785	DEVMETHOD(device_detach,    ahci_detach),
786	DEVMETHOD(device_suspend,   ahci_suspend),
787	DEVMETHOD(device_resume,    ahci_resume),
788	DEVMETHOD(bus_print_child,  ahci_print_child),
789	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
790	DEVMETHOD(bus_release_resource,     ahci_release_resource),
791	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
792	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
793	{ 0, 0 }
794};
795static driver_t ahci_driver = {
796        "ahci",
797        ahci_methods,
798        sizeof(struct ahci_controller)
799};
800DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
801static device_method_t ahci_ata_methods[] = {
802	DEVMETHOD(device_probe,     ahci_ata_probe),
803	DEVMETHOD(device_attach,    ahci_attach),
804	DEVMETHOD(device_detach,    ahci_detach),
805	DEVMETHOD(device_suspend,   ahci_suspend),
806	DEVMETHOD(device_resume,    ahci_resume),
807	DEVMETHOD(bus_print_child,  ahci_print_child),
808	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
809	DEVMETHOD(bus_release_resource,     ahci_release_resource),
810	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
811	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
812	{ 0, 0 }
813};
814static driver_t ahci_ata_driver = {
815        "ahci",
816        ahci_ata_methods,
817        sizeof(struct ahci_controller)
818};
819DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
820MODULE_VERSION(ahci, 1);
821MODULE_DEPEND(ahci, cam, 1, 1, 1);
822
823static int
824ahci_ch_probe(device_t dev)
825{
826
827	device_set_desc_copy(dev, "AHCI channel");
828	return (0);
829}
830
831static int
832ahci_ch_attach(device_t dev)
833{
834	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
835	struct ahci_channel *ch = device_get_softc(dev);
836	struct cam_devq *devq;
837	int rid, error, i, sata_rev = 0;
838	u_int32_t version;
839
840	ch->dev = dev;
841	ch->unit = (intptr_t)device_get_ivars(dev);
842	ch->caps = ctlr->caps;
843	ch->caps2 = ctlr->caps2;
844	ch->quirks = ctlr->quirks;
845	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
846	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
847	resource_int_value(device_get_name(dev),
848	    device_get_unit(dev), "pm_level", &ch->pm_level);
849	if (ch->pm_level > 3)
850		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
851	/* Limit speed for my onboard JMicron external port.
852	 * It is not eSATA really. */
853	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
854	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
855	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
856	    ch->unit == 0)
857		sata_rev = 1;
858	if (ch->quirks & AHCI_Q_SATA2)
859		sata_rev = 2;
860	resource_int_value(device_get_name(dev),
861	    device_get_unit(dev), "sata_rev", &sata_rev);
862	for (i = 0; i < 16; i++) {
863		ch->user[i].revision = sata_rev;
864		ch->user[i].mode = 0;
865		ch->user[i].bytecount = 8192;
866		ch->user[i].tags = ch->numslots;
867		ch->user[i].caps = 0;
868		ch->curr[i] = ch->user[i];
869		if (ch->pm_level) {
870			ch->user[i].caps = CTS_SATA_CAPS_H_PMREQ |
871			    CTS_SATA_CAPS_H_APST |
872			    CTS_SATA_CAPS_D_PMREQ | CTS_SATA_CAPS_D_APST;
873		}
874		ch->user[i].caps |= CTS_SATA_CAPS_H_DMAAA;
875	}
876	rid = ch->unit;
877	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
878	    &rid, RF_ACTIVE)))
879		return (ENXIO);
880	ahci_dmainit(dev);
881	ahci_slotsalloc(dev);
882	ahci_ch_init(dev);
883	mtx_lock(&ch->mtx);
884	rid = ATA_IRQ_RID;
885	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
886	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
887		bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
888		device_printf(dev, "Unable to map interrupt\n");
889		return (ENXIO);
890	}
891	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
892	    ahci_ch_intr_locked, dev, &ch->ih))) {
893		device_printf(dev, "Unable to setup interrupt\n");
894		error = ENXIO;
895		goto err1;
896	}
897	ch->chcaps = ATA_INL(ch->r_mem, AHCI_P_CMD);
898	version = ATA_INL(ctlr->r_mem, AHCI_VS);
899	if (version < 0x00010020 && (ctlr->caps & AHCI_CAP_FBSS))
900		ch->chcaps |= AHCI_P_CMD_FBSCP;
901	if (bootverbose) {
902		device_printf(dev, "Caps:%s%s%s%s%s\n",
903		    (ch->chcaps & AHCI_P_CMD_HPCP) ? " HPCP":"",
904		    (ch->chcaps & AHCI_P_CMD_MPSP) ? " MPSP":"",
905		    (ch->chcaps & AHCI_P_CMD_CPD) ? " CPD":"",
906		    (ch->chcaps & AHCI_P_CMD_ESP) ? " ESP":"",
907		    (ch->chcaps & AHCI_P_CMD_FBSCP) ? " FBSCP":"");
908	}
909	/* Create the device queue for our SIM. */
910	devq = cam_simq_alloc(ch->numslots);
911	if (devq == NULL) {
912		device_printf(dev, "Unable to allocate simq\n");
913		error = ENOMEM;
914		goto err1;
915	}
916	/* Construct SIM entry */
917	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
918	    device_get_unit(dev), &ch->mtx,
919	    min(2, ch->numslots),
920	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
921	    devq);
922	if (ch->sim == NULL) {
923		device_printf(dev, "unable to allocate sim\n");
924		error = ENOMEM;
925		goto err2;
926	}
927	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
928		device_printf(dev, "unable to register xpt bus\n");
929		error = ENXIO;
930		goto err2;
931	}
932	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
933	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
934		device_printf(dev, "unable to create path\n");
935		error = ENXIO;
936		goto err3;
937	}
938	if (ch->pm_level > 3) {
939		callout_reset(&ch->pm_timer,
940		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
941		    ahci_ch_pm, dev);
942	}
943	mtx_unlock(&ch->mtx);
944	return (0);
945
946err3:
947	xpt_bus_deregister(cam_sim_path(ch->sim));
948err2:
949	cam_sim_free(ch->sim, /*free_devq*/TRUE);
950err1:
951	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
952	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
953	mtx_unlock(&ch->mtx);
954	return (error);
955}
956
957static int
958ahci_ch_detach(device_t dev)
959{
960	struct ahci_channel *ch = device_get_softc(dev);
961
962	mtx_lock(&ch->mtx);
963	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
964	xpt_free_path(ch->path);
965	xpt_bus_deregister(cam_sim_path(ch->sim));
966	cam_sim_free(ch->sim, /*free_devq*/TRUE);
967	mtx_unlock(&ch->mtx);
968
969	if (ch->pm_level > 3)
970		callout_drain(&ch->pm_timer);
971	bus_teardown_intr(dev, ch->r_irq, ch->ih);
972	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
973
974	ahci_ch_deinit(dev);
975	ahci_slotsfree(dev);
976	ahci_dmafini(dev);
977
978	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
979	mtx_destroy(&ch->mtx);
980	return (0);
981}
982
983static int
984ahci_ch_init(device_t dev)
985{
986	struct ahci_channel *ch = device_get_softc(dev);
987	uint64_t work;
988
989	/* Disable port interrupts */
990	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
991	/* Setup work areas */
992	work = ch->dma.work_bus + AHCI_CL_OFFSET;
993	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
994	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
995	work = ch->dma.rfis_bus;
996	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
997	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
998	/* Activate the channel and power/spin up device */
999	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
1000	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
1001	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
1002	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
1003	ahci_start_fr(dev);
1004	ahci_start(dev, 1);
1005	return (0);
1006}
1007
1008static int
1009ahci_ch_deinit(device_t dev)
1010{
1011	struct ahci_channel *ch = device_get_softc(dev);
1012
1013	/* Disable port interrupts. */
1014	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1015	/* Reset command register. */
1016	ahci_stop(dev);
1017	ahci_stop_fr(dev);
1018	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
1019	/* Allow everything, including partial and slumber modes. */
1020	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
1021	/* Request slumber mode transition and give some time to get there. */
1022	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
1023	DELAY(100);
1024	/* Disable PHY. */
1025	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
1026	return (0);
1027}
1028
1029static int
1030ahci_ch_suspend(device_t dev)
1031{
1032	struct ahci_channel *ch = device_get_softc(dev);
1033
1034	mtx_lock(&ch->mtx);
1035	xpt_freeze_simq(ch->sim, 1);
1036	while (ch->oslots)
1037		msleep(ch, &ch->mtx, PRIBIO, "ahcisusp", hz/100);
1038	ahci_ch_deinit(dev);
1039	mtx_unlock(&ch->mtx);
1040	return (0);
1041}
1042
1043static int
1044ahci_ch_resume(device_t dev)
1045{
1046	struct ahci_channel *ch = device_get_softc(dev);
1047
1048	mtx_lock(&ch->mtx);
1049	ahci_ch_init(dev);
1050	ahci_reset(dev);
1051	xpt_release_simq(ch->sim, TRUE);
1052	mtx_unlock(&ch->mtx);
1053	return (0);
1054}
1055
1056devclass_t ahcich_devclass;
1057static device_method_t ahcich_methods[] = {
1058	DEVMETHOD(device_probe,     ahci_ch_probe),
1059	DEVMETHOD(device_attach,    ahci_ch_attach),
1060	DEVMETHOD(device_detach,    ahci_ch_detach),
1061	DEVMETHOD(device_suspend,   ahci_ch_suspend),
1062	DEVMETHOD(device_resume,    ahci_ch_resume),
1063	{ 0, 0 }
1064};
1065static driver_t ahcich_driver = {
1066        "ahcich",
1067        ahcich_methods,
1068        sizeof(struct ahci_channel)
1069};
1070DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
1071
1072struct ahci_dc_cb_args {
1073	bus_addr_t maddr;
1074	int error;
1075};
1076
1077static void
1078ahci_dmainit(device_t dev)
1079{
1080	struct ahci_channel *ch = device_get_softc(dev);
1081	struct ahci_dc_cb_args dcba;
1082	size_t rfsize;
1083
1084	if (ch->caps & AHCI_CAP_64BIT)
1085		ch->dma.max_address = BUS_SPACE_MAXADDR;
1086	else
1087		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
1088	/* Command area. */
1089	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
1090	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1091	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
1092	    0, NULL, NULL, &ch->dma.work_tag))
1093		goto error;
1094	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
1095	    &ch->dma.work_map))
1096		goto error;
1097	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
1098	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1099		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1100		goto error;
1101	}
1102	ch->dma.work_bus = dcba.maddr;
1103	/* FIS receive area. */
1104	if (ch->chcaps & AHCI_P_CMD_FBSCP)
1105	    rfsize = 4096;
1106	else
1107	    rfsize = 256;
1108	if (bus_dma_tag_create(bus_get_dma_tag(dev), rfsize, 0,
1109	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1110	    NULL, NULL, rfsize, 1, rfsize,
1111	    0, NULL, NULL, &ch->dma.rfis_tag))
1112		goto error;
1113	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1114	    &ch->dma.rfis_map))
1115		goto error;
1116	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1117	    rfsize, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1118		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1119		goto error;
1120	}
1121	ch->dma.rfis_bus = dcba.maddr;
1122	/* Data area. */
1123	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1124	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1125	    NULL, NULL,
1126	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1127	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1128	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1129		goto error;
1130	}
1131	return;
1132
1133error:
1134	device_printf(dev, "WARNING - DMA initialization failed\n");
1135	ahci_dmafini(dev);
1136}
1137
1138static void
1139ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1140{
1141	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1142
1143	if (!(dcba->error = error))
1144		dcba->maddr = segs[0].ds_addr;
1145}
1146
1147static void
1148ahci_dmafini(device_t dev)
1149{
1150	struct ahci_channel *ch = device_get_softc(dev);
1151
1152	if (ch->dma.data_tag) {
1153		bus_dma_tag_destroy(ch->dma.data_tag);
1154		ch->dma.data_tag = NULL;
1155	}
1156	if (ch->dma.rfis_bus) {
1157		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1158		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1159		ch->dma.rfis_bus = 0;
1160		ch->dma.rfis_map = NULL;
1161		ch->dma.rfis = NULL;
1162	}
1163	if (ch->dma.work_bus) {
1164		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1165		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1166		ch->dma.work_bus = 0;
1167		ch->dma.work_map = NULL;
1168		ch->dma.work = NULL;
1169	}
1170	if (ch->dma.work_tag) {
1171		bus_dma_tag_destroy(ch->dma.work_tag);
1172		ch->dma.work_tag = NULL;
1173	}
1174}
1175
1176static void
1177ahci_slotsalloc(device_t dev)
1178{
1179	struct ahci_channel *ch = device_get_softc(dev);
1180	int i;
1181
1182	/* Alloc and setup command/dma slots */
1183	bzero(ch->slot, sizeof(ch->slot));
1184	for (i = 0; i < ch->numslots; i++) {
1185		struct ahci_slot *slot = &ch->slot[i];
1186
1187		slot->dev = dev;
1188		slot->slot = i;
1189		slot->state = AHCI_SLOT_EMPTY;
1190		slot->ccb = NULL;
1191		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1192
1193		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1194			device_printf(ch->dev, "FAILURE - create data_map\n");
1195	}
1196}
1197
1198static void
1199ahci_slotsfree(device_t dev)
1200{
1201	struct ahci_channel *ch = device_get_softc(dev);
1202	int i;
1203
1204	/* Free all dma slots */
1205	for (i = 0; i < ch->numslots; i++) {
1206		struct ahci_slot *slot = &ch->slot[i];
1207
1208		callout_drain(&slot->timeout);
1209		if (slot->dma.data_map) {
1210			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1211			slot->dma.data_map = NULL;
1212		}
1213	}
1214}
1215
1216static void
1217ahci_phy_check_events(device_t dev, u_int32_t serr)
1218{
1219	struct ahci_channel *ch = device_get_softc(dev);
1220
1221	if ((serr & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
1222		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1223		union ccb *ccb;
1224
1225		if (bootverbose) {
1226			if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1227			    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1228			    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
1229				device_printf(dev, "CONNECT requested\n");
1230			} else
1231				device_printf(dev, "DISCONNECT requested\n");
1232		}
1233		ahci_reset(dev);
1234		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1235			return;
1236		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1237		    cam_sim_path(ch->sim),
1238		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1239			xpt_free_ccb(ccb);
1240			return;
1241		}
1242		xpt_rescan(ccb);
1243	}
1244}
1245
1246static void
1247ahci_notify_events(device_t dev, u_int32_t status)
1248{
1249	struct ahci_channel *ch = device_get_softc(dev);
1250	struct cam_path *dpath;
1251	int i;
1252
1253	if (ch->caps & AHCI_CAP_SSNTF)
1254		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1255	if (bootverbose)
1256		device_printf(dev, "SNTF 0x%04x\n", status);
1257	for (i = 0; i < 16; i++) {
1258		if ((status & (1 << i)) == 0)
1259			continue;
1260		if (xpt_create_path(&dpath, NULL,
1261		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1262			xpt_async(AC_SCSI_AEN, dpath, NULL);
1263			xpt_free_path(dpath);
1264		}
1265	}
1266}
1267
1268static void
1269ahci_ch_intr_locked(void *data)
1270{
1271	device_t dev = (device_t)data;
1272	struct ahci_channel *ch = device_get_softc(dev);
1273
1274	mtx_lock(&ch->mtx);
1275	ahci_ch_intr(data);
1276	mtx_unlock(&ch->mtx);
1277}
1278
1279static void
1280ahci_ch_pm(void *arg)
1281{
1282	device_t dev = (device_t)arg;
1283	struct ahci_channel *ch = device_get_softc(dev);
1284	uint32_t work;
1285
1286	if (ch->numrslots != 0)
1287		return;
1288	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1289	if (ch->pm_level == 4)
1290		work |= AHCI_P_CMD_PARTIAL;
1291	else
1292		work |= AHCI_P_CMD_SLUMBER;
1293	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1294}
1295
1296static void
1297ahci_ch_intr(void *data)
1298{
1299	device_t dev = (device_t)data;
1300	struct ahci_channel *ch = device_get_softc(dev);
1301	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1302	enum ahci_err_type et;
1303	int i, ccs, port;
1304
1305	/* Read and clear interrupt statuses. */
1306	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1307	if (istatus == 0)
1308		return;
1309	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1310	/* Read command statuses. */
1311	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1312	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1313	if (istatus & AHCI_P_IX_SDB) {
1314		if (ch->caps & AHCI_CAP_SSNTF)
1315			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1316		else if (ch->fbs_enabled) {
1317			u_int8_t *fis = ch->dma.rfis + 0x58;
1318
1319			for (i = 0; i < 16; i++) {
1320				if (fis[1] & 0x80) {
1321					fis[1] &= 0x7f;
1322	    				sntf |= 1 << i;
1323	    			}
1324	    			fis += 256;
1325	    		}
1326		} else {
1327			u_int8_t *fis = ch->dma.rfis + 0x58;
1328
1329			if (fis[1] & 0x80)
1330				sntf = (1 << (fis[1] & 0x0f));
1331		}
1332	}
1333	/* Process PHY events */
1334	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1335	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1336		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1337		if (serr) {
1338			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1339			ahci_phy_check_events(dev, serr);
1340		}
1341	}
1342	/* Process command errors */
1343	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1344	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1345		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1346		    >> AHCI_P_CMD_CCS_SHIFT;
1347//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1348//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1349//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1350		port = -1;
1351		if (ch->fbs_enabled) {
1352			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1353			if (fbs & AHCI_P_FBS_SDE) {
1354				port = (fbs & AHCI_P_FBS_DWE)
1355				    >> AHCI_P_FBS_DWE_SHIFT;
1356			} else {
1357				for (i = 0; i < 16; i++) {
1358					if (ch->numrslotspd[i] == 0)
1359						continue;
1360					if (port == -1)
1361						port = i;
1362					else if (port != i) {
1363						port = -2;
1364						break;
1365					}
1366				}
1367			}
1368		}
1369		err = ch->rslots & (cstatus | sstatus);
1370	} else {
1371		ccs = 0;
1372		err = 0;
1373		port = -1;
1374	}
1375	/* Complete all successfull commands. */
1376	ok = ch->rslots & ~(cstatus | sstatus);
1377	for (i = 0; i < ch->numslots; i++) {
1378		if ((ok >> i) & 1)
1379			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1380	}
1381	/* On error, complete the rest of commands with error statuses. */
1382	if (err) {
1383		if (ch->frozen) {
1384			union ccb *fccb = ch->frozen;
1385			ch->frozen = NULL;
1386			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1387			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1388				xpt_freeze_devq(fccb->ccb_h.path, 1);
1389				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1390			}
1391			xpt_done(fccb);
1392		}
1393		for (i = 0; i < ch->numslots; i++) {
1394			/* XXX: reqests in loading state. */
1395			if (((err >> i) & 1) == 0)
1396				continue;
1397			if (port >= 0 &&
1398			    ch->slot[i].ccb->ccb_h.target_id != port)
1399				continue;
1400			if (istatus & AHCI_P_IX_TFE) {
1401			    if (port != -2) {
1402				/* Task File Error */
1403				if (ch->numtslotspd[
1404				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1405					/* Untagged operation. */
1406					if (i == ccs)
1407						et = AHCI_ERR_TFE;
1408					else
1409						et = AHCI_ERR_INNOCENT;
1410				} else {
1411					/* Tagged operation. */
1412					et = AHCI_ERR_NCQ;
1413				}
1414			    } else {
1415				et = AHCI_ERR_TFE;
1416				ch->fatalerr = 1;
1417			    }
1418			} else if (istatus & AHCI_P_IX_IF) {
1419				if (ch->numtslots == 0 && i != ccs && port != -2)
1420					et = AHCI_ERR_INNOCENT;
1421				else
1422					et = AHCI_ERR_SATA;
1423			} else
1424				et = AHCI_ERR_INVALID;
1425			ahci_end_transaction(&ch->slot[i], et);
1426		}
1427		/*
1428		 * We can't reinit port if there are some other
1429		 * commands active, use resume to complete them.
1430		 */
1431		if (ch->rslots != 0)
1432			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1433	}
1434	/* Process NOTIFY events */
1435	if (sntf)
1436		ahci_notify_events(dev, sntf);
1437}
1438
1439/* Must be called with channel locked. */
1440static int
1441ahci_check_collision(device_t dev, union ccb *ccb)
1442{
1443	struct ahci_channel *ch = device_get_softc(dev);
1444	int t = ccb->ccb_h.target_id;
1445
1446	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1447	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1448		/* Tagged command while we have no supported tag free. */
1449		if (((~ch->oslots) & (0xffffffff >> (32 -
1450		    ch->curr[t].tags))) == 0)
1451			return (1);
1452		/* If we have FBS */
1453		if (ch->fbs_enabled) {
1454			/* Tagged command while untagged are active. */
1455			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1456				return (1);
1457		} else {
1458			/* Tagged command while untagged are active. */
1459			if (ch->numrslots != 0 && ch->numtslots == 0)
1460				return (1);
1461			/* Tagged command while tagged to other target is active. */
1462			if (ch->numtslots != 0 &&
1463			    ch->taggedtarget != ccb->ccb_h.target_id)
1464				return (1);
1465		}
1466	} else {
1467		/* If we have FBS */
1468		if (ch->fbs_enabled) {
1469			/* Untagged command while tagged are active. */
1470			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1471				return (1);
1472		} else {
1473			/* Untagged command while tagged are active. */
1474			if (ch->numrslots != 0 && ch->numtslots != 0)
1475				return (1);
1476		}
1477	}
1478	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1479	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1480		/* Atomic command while anything active. */
1481		if (ch->numrslots != 0)
1482			return (1);
1483	}
1484       /* We have some atomic command running. */
1485       if (ch->aslots != 0)
1486               return (1);
1487	return (0);
1488}
1489
1490/* Must be called with channel locked. */
1491static void
1492ahci_begin_transaction(device_t dev, union ccb *ccb)
1493{
1494	struct ahci_channel *ch = device_get_softc(dev);
1495	struct ahci_slot *slot;
1496	int tag, tags;
1497
1498	/* Choose empty slot. */
1499	tags = ch->numslots;
1500	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1501	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1502		tags = ch->curr[ccb->ccb_h.target_id].tags;
1503	tag = ch->lastslot;
1504	while (1) {
1505		if (tag >= tags)
1506			tag = 0;
1507		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1508			break;
1509		tag++;
1510	};
1511	ch->lastslot = tag;
1512	/* Occupy chosen slot. */
1513	slot = &ch->slot[tag];
1514	slot->ccb = ccb;
1515	/* Stop PM timer. */
1516	if (ch->numrslots == 0 && ch->pm_level > 3)
1517		callout_stop(&ch->pm_timer);
1518	/* Update channel stats. */
1519	ch->oslots |= (1 << slot->slot);
1520	ch->numrslots++;
1521	ch->numrslotspd[ccb->ccb_h.target_id]++;
1522	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1523	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1524		ch->numtslots++;
1525		ch->numtslotspd[ccb->ccb_h.target_id]++;
1526		ch->taggedtarget = ccb->ccb_h.target_id;
1527	}
1528	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1529	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1530		ch->aslots |= (1 << slot->slot);
1531	slot->dma.nsegs = 0;
1532	/* If request moves data, setup and load SG list */
1533	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1534		void *buf;
1535		bus_size_t size;
1536
1537		slot->state = AHCI_SLOT_LOADING;
1538		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1539			buf = ccb->ataio.data_ptr;
1540			size = ccb->ataio.dxfer_len;
1541		} else {
1542			buf = ccb->csio.data_ptr;
1543			size = ccb->csio.dxfer_len;
1544		}
1545		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1546		    buf, size, ahci_dmasetprd, slot, 0);
1547	} else
1548		ahci_execute_transaction(slot);
1549}
1550
1551/* Locked by busdma engine. */
1552static void
1553ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1554{
1555	struct ahci_slot *slot = arg;
1556	struct ahci_channel *ch = device_get_softc(slot->dev);
1557	struct ahci_cmd_tab *ctp;
1558	struct ahci_dma_prd *prd;
1559	int i;
1560
1561	if (error) {
1562		device_printf(slot->dev, "DMA load error\n");
1563		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1564		return;
1565	}
1566	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1567	/* Get a piece of the workspace for this request */
1568	ctp = (struct ahci_cmd_tab *)
1569		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1570	/* Fill S/G table */
1571	prd = &ctp->prd_tab[0];
1572	for (i = 0; i < nsegs; i++) {
1573		prd[i].dba = htole64(segs[i].ds_addr);
1574		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1575	}
1576	slot->dma.nsegs = nsegs;
1577	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1578	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1579	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1580	ahci_execute_transaction(slot);
1581}
1582
1583/* Must be called with channel locked. */
1584static void
1585ahci_execute_transaction(struct ahci_slot *slot)
1586{
1587	device_t dev = slot->dev;
1588	struct ahci_channel *ch = device_get_softc(dev);
1589	struct ahci_cmd_tab *ctp;
1590	struct ahci_cmd_list *clp;
1591	union ccb *ccb = slot->ccb;
1592	int port = ccb->ccb_h.target_id & 0x0f;
1593	int fis_size, i;
1594	uint8_t *fis = ch->dma.rfis + 0x40;
1595	uint8_t val;
1596
1597	/* Get a piece of the workspace for this request */
1598	ctp = (struct ahci_cmd_tab *)
1599		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1600	/* Setup the FIS for this request */
1601	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1602		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1603		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1604		return;
1605	}
1606	/* Setup the command list entry */
1607	clp = (struct ahci_cmd_list *)
1608	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1609	clp->prd_length = slot->dma.nsegs;
1610	clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1611		     (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1612		      (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1613		     (fis_size / sizeof(u_int32_t)) |
1614		     (port << 12);
1615	/* Special handling for Soft Reset command. */
1616	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1617	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1618		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1619			/* Kick controller into sane state */
1620			ahci_stop(dev);
1621			ahci_clo(dev);
1622			ahci_start(dev, 0);
1623			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1624		} else {
1625			/* Prepare FIS receive area for check. */
1626			for (i = 0; i < 20; i++)
1627				fis[i] = 0xff;
1628		}
1629	}
1630	clp->bytecount = 0;
1631	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1632				  (AHCI_CT_SIZE * slot->slot));
1633	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1634	    BUS_DMASYNC_PREWRITE);
1635	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1636	    BUS_DMASYNC_PREREAD);
1637	/* Set ACTIVE bit for NCQ commands. */
1638	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1639	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1640		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1641	}
1642	/* If FBS is enabled, set PMP port. */
1643	if (ch->fbs_enabled) {
1644		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1645		    (port << AHCI_P_FBS_DEV_SHIFT));
1646	}
1647	/* Issue command to the controller. */
1648	slot->state = AHCI_SLOT_RUNNING;
1649	ch->rslots |= (1 << slot->slot);
1650	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1651	/* Device reset commands doesn't interrupt. Poll them. */
1652	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1653	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1654	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1655		int count, timeout = ccb->ccb_h.timeout;
1656		enum ahci_err_type et = AHCI_ERR_NONE;
1657
1658		for (count = 0; count < timeout; count++) {
1659			DELAY(1000);
1660			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1661				break;
1662			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1663				device_printf(ch->dev,
1664				    "Poll error on slot %d, TFD: %04x\n",
1665				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1666				et = AHCI_ERR_TFE;
1667				break;
1668			}
1669			/* Workaround for ATI SB600/SB700 chipsets. */
1670			if (ccb->ccb_h.target_id == 15 &&
1671			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1672			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1673				et = AHCI_ERR_TIMEOUT;
1674				break;
1675			}
1676		}
1677		if (timeout && (count >= timeout)) {
1678			device_printf(ch->dev,
1679			    "Poll timeout on slot %d\n", slot->slot);
1680			device_printf(dev, "is %08x cs %08x ss %08x "
1681			    "rs %08x tfd %02x serr %08x\n",
1682			    ATA_INL(ch->r_mem, AHCI_P_IS),
1683			    ATA_INL(ch->r_mem, AHCI_P_CI),
1684			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1685			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1686			    ATA_INL(ch->r_mem, AHCI_P_SERR));
1687			et = AHCI_ERR_TIMEOUT;
1688		}
1689		/* Marvell controllers do not wait for readyness. */
1690		if ((ch->quirks & AHCI_Q_NOBSYRES) &&
1691		    (ccb->ccb_h.func_code == XPT_ATA_IO) &&
1692		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1693		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1694			while ((val = fis[2]) & (ATA_S_BUSY | ATA_S_DRQ)) {
1695				DELAY(1000);
1696				if (count++ >= timeout) {
1697					device_printf(dev, "device is not "
1698					    "ready after soft-reset: "
1699					    "tfd = %08x\n", val);
1700	    				et = AHCI_ERR_TIMEOUT;
1701	    				break;
1702				}
1703			}
1704		}
1705		ahci_end_transaction(slot, et);
1706		/* Kick controller into sane state and enable FBS. */
1707		if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1708		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1709		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1710			ahci_stop(ch->dev);
1711			ahci_start(ch->dev, 1);
1712		}
1713		return;
1714	}
1715	/* Start command execution timeout */
1716	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1717	    (timeout_t*)ahci_timeout, slot);
1718	return;
1719}
1720
1721/* Must be called with channel locked. */
1722static void
1723ahci_process_timeout(device_t dev)
1724{
1725	struct ahci_channel *ch = device_get_softc(dev);
1726	int i;
1727
1728	mtx_assert(&ch->mtx, MA_OWNED);
1729	/* Handle the rest of commands. */
1730	for (i = 0; i < ch->numslots; i++) {
1731		/* Do we have a running request on slot? */
1732		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1733			continue;
1734		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1735	}
1736}
1737
1738/* Must be called with channel locked. */
1739static void
1740ahci_rearm_timeout(device_t dev)
1741{
1742	struct ahci_channel *ch = device_get_softc(dev);
1743	int i;
1744
1745	mtx_assert(&ch->mtx, MA_OWNED);
1746	for (i = 0; i < ch->numslots; i++) {
1747		struct ahci_slot *slot = &ch->slot[i];
1748
1749		/* Do we have a running request on slot? */
1750		if (slot->state < AHCI_SLOT_RUNNING)
1751			continue;
1752		if ((ch->toslots & (1 << i)) == 0)
1753			continue;
1754		callout_reset(&slot->timeout,
1755		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1756		    (timeout_t*)ahci_timeout, slot);
1757	}
1758}
1759
1760/* Locked by callout mechanism. */
1761static void
1762ahci_timeout(struct ahci_slot *slot)
1763{
1764	device_t dev = slot->dev;
1765	struct ahci_channel *ch = device_get_softc(dev);
1766	uint32_t sstatus;
1767	int ccs;
1768	int i;
1769
1770	/* Check for stale timeout. */
1771	if (slot->state < AHCI_SLOT_RUNNING)
1772		return;
1773
1774	/* Check if slot was not being executed last time we checked. */
1775	if (slot->state < AHCI_SLOT_EXECUTING) {
1776		/* Check if slot started executing. */
1777		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1778		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1779		    >> AHCI_P_CMD_CCS_SHIFT;
1780		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1781		    ch->fbs_enabled)
1782			slot->state = AHCI_SLOT_EXECUTING;
1783
1784		callout_reset(&slot->timeout,
1785		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1786		    (timeout_t*)ahci_timeout, slot);
1787		return;
1788	}
1789
1790	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1791	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1792	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1793	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1794	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1795
1796	/* Handle frozen command. */
1797	if (ch->frozen) {
1798		union ccb *fccb = ch->frozen;
1799		ch->frozen = NULL;
1800		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1801		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1802			xpt_freeze_devq(fccb->ccb_h.path, 1);
1803			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1804		}
1805		xpt_done(fccb);
1806	}
1807	if (!ch->fbs_enabled) {
1808		/* Without FBS we know real timeout source. */
1809		ch->fatalerr = 1;
1810		/* Handle command with timeout. */
1811		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1812		/* Handle the rest of commands. */
1813		for (i = 0; i < ch->numslots; i++) {
1814			/* Do we have a running request on slot? */
1815			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1816				continue;
1817			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1818		}
1819	} else {
1820		/* With FBS we wait for other commands timeout and pray. */
1821		if (ch->toslots == 0)
1822			xpt_freeze_simq(ch->sim, 1);
1823		ch->toslots |= (1 << slot->slot);
1824		if ((ch->rslots & ~ch->toslots) == 0)
1825			ahci_process_timeout(dev);
1826		else
1827			device_printf(dev, " ... waiting for slots %08x\n",
1828			    ch->rslots & ~ch->toslots);
1829	}
1830}
1831
1832/* Must be called with channel locked. */
1833static void
1834ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1835{
1836	device_t dev = slot->dev;
1837	struct ahci_channel *ch = device_get_softc(dev);
1838	union ccb *ccb = slot->ccb;
1839
1840	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1841	    BUS_DMASYNC_POSTWRITE);
1842	/* Read result registers to the result struct
1843	 * May be incorrect if several commands finished same time,
1844	 * so read only when sure or have to.
1845	 */
1846	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1847		struct ata_res *res = &ccb->ataio.res;
1848
1849		if ((et == AHCI_ERR_TFE) ||
1850		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1851			u_int8_t *fis = ch->dma.rfis + 0x40;
1852
1853			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1854			    BUS_DMASYNC_POSTREAD);
1855			if (ch->fbs_enabled) {
1856				fis += ccb->ccb_h.target_id * 256;
1857				res->status = fis[2];
1858				res->error = fis[3];
1859			} else {
1860				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1861
1862				res->status = tfd;
1863				res->error = tfd >> 8;
1864			}
1865			res->lba_low = fis[4];
1866			res->lba_mid = fis[5];
1867			res->lba_high = fis[6];
1868			res->device = fis[7];
1869			res->lba_low_exp = fis[8];
1870			res->lba_mid_exp = fis[9];
1871			res->lba_high_exp = fis[10];
1872			res->sector_count = fis[12];
1873			res->sector_count_exp = fis[13];
1874		} else
1875			bzero(res, sizeof(*res));
1876	}
1877	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1878		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1879		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1880		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1881		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1882	}
1883	if (et != AHCI_ERR_NONE)
1884		ch->eslots |= (1 << slot->slot);
1885	/* In case of error, freeze device for proper recovery. */
1886	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1887	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1888		xpt_freeze_devq(ccb->ccb_h.path, 1);
1889		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1890	}
1891	/* Set proper result status. */
1892	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1893	switch (et) {
1894	case AHCI_ERR_NONE:
1895		ccb->ccb_h.status |= CAM_REQ_CMP;
1896		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1897			ccb->csio.scsi_status = SCSI_STATUS_OK;
1898		break;
1899	case AHCI_ERR_INVALID:
1900		ch->fatalerr = 1;
1901		ccb->ccb_h.status |= CAM_REQ_INVALID;
1902		break;
1903	case AHCI_ERR_INNOCENT:
1904		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1905		break;
1906	case AHCI_ERR_TFE:
1907	case AHCI_ERR_NCQ:
1908		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1909			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1910			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1911		} else {
1912			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1913		}
1914		break;
1915	case AHCI_ERR_SATA:
1916		ch->fatalerr = 1;
1917		if (!ch->readlog) {
1918			xpt_freeze_simq(ch->sim, 1);
1919			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1920			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1921		}
1922		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1923		break;
1924	case AHCI_ERR_TIMEOUT:
1925		if (!ch->readlog) {
1926			xpt_freeze_simq(ch->sim, 1);
1927			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1928			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1929		}
1930		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1931		break;
1932	default:
1933		ch->fatalerr = 1;
1934		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1935	}
1936	/* Free slot. */
1937	ch->oslots &= ~(1 << slot->slot);
1938	ch->rslots &= ~(1 << slot->slot);
1939	ch->aslots &= ~(1 << slot->slot);
1940	if (et != AHCI_ERR_TIMEOUT) {
1941		if (ch->toslots == (1 << slot->slot))
1942			xpt_release_simq(ch->sim, TRUE);
1943		ch->toslots &= ~(1 << slot->slot);
1944	}
1945	slot->state = AHCI_SLOT_EMPTY;
1946	slot->ccb = NULL;
1947	/* Update channel stats. */
1948	ch->numrslots--;
1949	ch->numrslotspd[ccb->ccb_h.target_id]--;
1950	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1951	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1952		ch->numtslots--;
1953		ch->numtslotspd[ccb->ccb_h.target_id]--;
1954	}
1955	/* If it was first request of reset sequence and there is no error,
1956	 * proceed to second request. */
1957	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1958	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1959	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1960	    et == AHCI_ERR_NONE) {
1961		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1962		ahci_begin_transaction(dev, ccb);
1963		return;
1964	}
1965	/* If it was our READ LOG command - process it. */
1966	if (ch->readlog) {
1967		ahci_process_read_log(dev, ccb);
1968	/* If it was NCQ command error, put result on hold. */
1969	} else if (et == AHCI_ERR_NCQ) {
1970		ch->hold[slot->slot] = ccb;
1971		ch->numhslots++;
1972	} else
1973		xpt_done(ccb);
1974	/* Unfreeze frozen command. */
1975	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
1976		union ccb *fccb = ch->frozen;
1977		ch->frozen = NULL;
1978		ahci_begin_transaction(dev, fccb);
1979		xpt_release_simq(ch->sim, TRUE);
1980	}
1981	/* If we have no other active commands, ... */
1982	if (ch->rslots == 0) {
1983		/* if there was fatal error - reset port. */
1984		if (ch->toslots != 0 || ch->fatalerr) {
1985			ahci_reset(dev);
1986		} else {
1987			/* if we have slots in error, we can reinit port. */
1988			if (ch->eslots != 0) {
1989				ahci_stop(dev);
1990				ahci_start(dev, 1);
1991			}
1992			/* if there commands on hold, we can do READ LOG. */
1993			if (!ch->readlog && ch->numhslots)
1994				ahci_issue_read_log(dev);
1995		}
1996	/* If all the rest of commands are in timeout - give them chance. */
1997	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1998	    et != AHCI_ERR_TIMEOUT)
1999		ahci_rearm_timeout(dev);
2000	/* Start PM timer. */
2001	if (ch->numrslots == 0 && ch->pm_level > 3 &&
2002	    (ch->curr[ch->pm_present ? 15 : 0].caps & CTS_SATA_CAPS_D_PMREQ)) {
2003		callout_schedule(&ch->pm_timer,
2004		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
2005	}
2006}
2007
2008static void
2009ahci_issue_read_log(device_t dev)
2010{
2011	struct ahci_channel *ch = device_get_softc(dev);
2012	union ccb *ccb;
2013	struct ccb_ataio *ataio;
2014	int i;
2015
2016	ch->readlog = 1;
2017	/* Find some holden command. */
2018	for (i = 0; i < ch->numslots; i++) {
2019		if (ch->hold[i])
2020			break;
2021	}
2022	ccb = xpt_alloc_ccb_nowait();
2023	if (ccb == NULL) {
2024		device_printf(dev, "Unable allocate READ LOG command");
2025		return; /* XXX */
2026	}
2027	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
2028	ccb->ccb_h.func_code = XPT_ATA_IO;
2029	ccb->ccb_h.flags = CAM_DIR_IN;
2030	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
2031	ataio = &ccb->ataio;
2032	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
2033	if (ataio->data_ptr == NULL) {
2034		device_printf(dev, "Unable allocate memory for READ LOG command");
2035		return; /* XXX */
2036	}
2037	ataio->dxfer_len = 512;
2038	bzero(&ataio->cmd, sizeof(ataio->cmd));
2039	ataio->cmd.flags = CAM_ATAIO_48BIT;
2040	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
2041	ataio->cmd.sector_count = 1;
2042	ataio->cmd.sector_count_exp = 0;
2043	ataio->cmd.lba_low = 0x10;
2044	ataio->cmd.lba_mid = 0;
2045	ataio->cmd.lba_mid_exp = 0;
2046	/* Freeze SIM while doing READ LOG EXT. */
2047	xpt_freeze_simq(ch->sim, 1);
2048	ahci_begin_transaction(dev, ccb);
2049}
2050
2051static void
2052ahci_process_read_log(device_t dev, union ccb *ccb)
2053{
2054	struct ahci_channel *ch = device_get_softc(dev);
2055	uint8_t *data;
2056	struct ata_res *res;
2057	int i;
2058
2059	ch->readlog = 0;
2060
2061	data = ccb->ataio.data_ptr;
2062	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2063	    (data[0] & 0x80) == 0) {
2064		for (i = 0; i < ch->numslots; i++) {
2065			if (!ch->hold[i])
2066				continue;
2067			if ((data[0] & 0x1F) == i) {
2068				res = &ch->hold[i]->ataio.res;
2069				res->status = data[2];
2070				res->error = data[3];
2071				res->lba_low = data[4];
2072				res->lba_mid = data[5];
2073				res->lba_high = data[6];
2074				res->device = data[7];
2075				res->lba_low_exp = data[8];
2076				res->lba_mid_exp = data[9];
2077				res->lba_high_exp = data[10];
2078				res->sector_count = data[12];
2079				res->sector_count_exp = data[13];
2080			} else {
2081				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2082				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2083			}
2084			xpt_done(ch->hold[i]);
2085			ch->hold[i] = NULL;
2086			ch->numhslots--;
2087		}
2088	} else {
2089		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2090			device_printf(dev, "Error while READ LOG EXT\n");
2091		else if ((data[0] & 0x80) == 0) {
2092			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
2093		}
2094		for (i = 0; i < ch->numslots; i++) {
2095			if (!ch->hold[i])
2096				continue;
2097			xpt_done(ch->hold[i]);
2098			ch->hold[i] = NULL;
2099			ch->numhslots--;
2100		}
2101	}
2102	free(ccb->ataio.data_ptr, M_AHCI);
2103	xpt_free_ccb(ccb);
2104	xpt_release_simq(ch->sim, TRUE);
2105}
2106
2107static void
2108ahci_start(device_t dev, int fbs)
2109{
2110	struct ahci_channel *ch = device_get_softc(dev);
2111	u_int32_t cmd;
2112
2113	/* Clear SATA error register */
2114	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2115	/* Clear any interrupts pending on this channel */
2116	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2117	/* Configure FIS-based switching if supported. */
2118	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2119		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2120		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2121		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2122	}
2123	/* Start operations on this channel */
2124	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2125	cmd &= ~AHCI_P_CMD_PMA;
2126	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2127	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2128}
2129
2130static void
2131ahci_stop(device_t dev)
2132{
2133	struct ahci_channel *ch = device_get_softc(dev);
2134	u_int32_t cmd;
2135	int timeout;
2136
2137	/* Kill all activity on this channel */
2138	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2139	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2140	/* Wait for activity stop. */
2141	timeout = 0;
2142	do {
2143		DELAY(1000);
2144		if (timeout++ > 1000) {
2145			device_printf(dev, "stopping AHCI engine failed\n");
2146			break;
2147		}
2148	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2149	ch->eslots = 0;
2150}
2151
2152static void
2153ahci_clo(device_t dev)
2154{
2155	struct ahci_channel *ch = device_get_softc(dev);
2156	u_int32_t cmd;
2157	int timeout;
2158
2159	/* Issue Command List Override if supported */
2160	if (ch->caps & AHCI_CAP_SCLO) {
2161		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2162		cmd |= AHCI_P_CMD_CLO;
2163		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2164		timeout = 0;
2165		do {
2166			DELAY(1000);
2167			if (timeout++ > 1000) {
2168			    device_printf(dev, "executing CLO failed\n");
2169			    break;
2170			}
2171		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2172	}
2173}
2174
2175static void
2176ahci_stop_fr(device_t dev)
2177{
2178	struct ahci_channel *ch = device_get_softc(dev);
2179	u_int32_t cmd;
2180	int timeout;
2181
2182	/* Kill all FIS reception on this channel */
2183	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2184	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2185	/* Wait for FIS reception stop. */
2186	timeout = 0;
2187	do {
2188		DELAY(1000);
2189		if (timeout++ > 1000) {
2190			device_printf(dev, "stopping AHCI FR engine failed\n");
2191			break;
2192		}
2193	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2194}
2195
2196static void
2197ahci_start_fr(device_t dev)
2198{
2199	struct ahci_channel *ch = device_get_softc(dev);
2200	u_int32_t cmd;
2201
2202	/* Start FIS reception on this channel */
2203	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2204	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2205}
2206
2207static int
2208ahci_wait_ready(device_t dev, int t)
2209{
2210	struct ahci_channel *ch = device_get_softc(dev);
2211	int timeout = 0;
2212	uint32_t val;
2213
2214	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2215	    (ATA_S_BUSY | ATA_S_DRQ)) {
2216		DELAY(1000);
2217		if (timeout++ > t) {
2218			device_printf(dev, "device is not ready (timeout %dms) "
2219			    "tfd = %08x\n", t, val);
2220			return (EBUSY);
2221		}
2222	}
2223	if (bootverbose)
2224		device_printf(dev, "ready wait time=%dms\n", timeout);
2225	return (0);
2226}
2227
2228static void
2229ahci_reset(device_t dev)
2230{
2231	struct ahci_channel *ch = device_get_softc(dev);
2232	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2233	int i;
2234
2235	xpt_freeze_simq(ch->sim, 1);
2236	if (bootverbose)
2237		device_printf(dev, "AHCI reset...\n");
2238	/* Requeue freezed command. */
2239	if (ch->frozen) {
2240		union ccb *fccb = ch->frozen;
2241		ch->frozen = NULL;
2242		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2243		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2244			xpt_freeze_devq(fccb->ccb_h.path, 1);
2245			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2246		}
2247		xpt_done(fccb);
2248	}
2249	/* Kill the engine and requeue all running commands. */
2250	ahci_stop(dev);
2251	for (i = 0; i < ch->numslots; i++) {
2252		/* Do we have a running request on slot? */
2253		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2254			continue;
2255		/* XXX; Commands in loading state. */
2256		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2257	}
2258	for (i = 0; i < ch->numslots; i++) {
2259		if (!ch->hold[i])
2260			continue;
2261		xpt_done(ch->hold[i]);
2262		ch->hold[i] = NULL;
2263		ch->numhslots--;
2264	}
2265	if (ch->toslots != 0)
2266		xpt_release_simq(ch->sim, TRUE);
2267	ch->eslots = 0;
2268	ch->toslots = 0;
2269	ch->fatalerr = 0;
2270	/* Tell the XPT about the event */
2271	xpt_async(AC_BUS_RESET, ch->path, NULL);
2272	/* Disable port interrupts */
2273	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2274	/* Reset and reconnect PHY, */
2275	if (!ahci_sata_phy_reset(dev)) {
2276		if (bootverbose)
2277			device_printf(dev,
2278			    "AHCI reset done: phy reset found no device\n");
2279		ch->devices = 0;
2280		/* Enable wanted port interrupts */
2281		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2282		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
2283		xpt_release_simq(ch->sim, TRUE);
2284		return;
2285	}
2286	/* Wait for clearing busy status. */
2287	if (ahci_wait_ready(dev, 15000))
2288		ahci_clo(dev);
2289	ahci_start(dev, 1);
2290	ch->devices = 1;
2291	/* Enable wanted port interrupts */
2292	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2293	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2294	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2295	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
2296	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2297	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2298	if (bootverbose)
2299		device_printf(dev, "AHCI reset done: device found\n");
2300	xpt_release_simq(ch->sim, TRUE);
2301}
2302
2303static int
2304ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2305{
2306	struct ahci_channel *ch = device_get_softc(dev);
2307	u_int8_t *fis = &ctp->cfis[0];
2308
2309	bzero(ctp->cfis, 64);
2310	fis[0] = 0x27;  		/* host to device */
2311	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2312	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2313		fis[1] |= 0x80;
2314		fis[2] = ATA_PACKET_CMD;
2315		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2316		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2317			fis[3] = ATA_F_DMA;
2318		else {
2319			fis[5] = ccb->csio.dxfer_len;
2320		        fis[6] = ccb->csio.dxfer_len >> 8;
2321		}
2322		fis[7] = ATA_D_LBA;
2323		fis[15] = ATA_A_4BIT;
2324		bzero(ctp->acmd, 32);
2325		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2326		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2327		    ctp->acmd, ccb->csio.cdb_len);
2328	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2329		fis[1] |= 0x80;
2330		fis[2] = ccb->ataio.cmd.command;
2331		fis[3] = ccb->ataio.cmd.features;
2332		fis[4] = ccb->ataio.cmd.lba_low;
2333		fis[5] = ccb->ataio.cmd.lba_mid;
2334		fis[6] = ccb->ataio.cmd.lba_high;
2335		fis[7] = ccb->ataio.cmd.device;
2336		fis[8] = ccb->ataio.cmd.lba_low_exp;
2337		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2338		fis[10] = ccb->ataio.cmd.lba_high_exp;
2339		fis[11] = ccb->ataio.cmd.features_exp;
2340		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2341			fis[12] = tag << 3;
2342			fis[13] = 0;
2343		} else {
2344			fis[12] = ccb->ataio.cmd.sector_count;
2345			fis[13] = ccb->ataio.cmd.sector_count_exp;
2346		}
2347		fis[15] = ATA_A_4BIT;
2348	} else {
2349		fis[15] = ccb->ataio.cmd.control;
2350	}
2351	return (20);
2352}
2353
2354static int
2355ahci_sata_connect(struct ahci_channel *ch)
2356{
2357	u_int32_t status;
2358	int timeout;
2359
2360	/* Wait up to 100ms for "connect well" */
2361	for (timeout = 0; timeout < 100 ; timeout++) {
2362		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2363		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2364		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2365		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2366			break;
2367		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2368			if (bootverbose) {
2369				device_printf(ch->dev, "SATA offline status=%08x\n",
2370				    status);
2371			}
2372			return (0);
2373		}
2374		DELAY(1000);
2375	}
2376	if (timeout >= 100) {
2377		if (bootverbose) {
2378			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2379			    status);
2380		}
2381		return (0);
2382	}
2383	if (bootverbose) {
2384		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2385		    timeout, status);
2386	}
2387	/* Clear SATA error register */
2388	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2389	return (1);
2390}
2391
2392static int
2393ahci_sata_phy_reset(device_t dev)
2394{
2395	struct ahci_channel *ch = device_get_softc(dev);
2396	int sata_rev;
2397	uint32_t val;
2398
2399	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2400	if (sata_rev == 1)
2401		val = ATA_SC_SPD_SPEED_GEN1;
2402	else if (sata_rev == 2)
2403		val = ATA_SC_SPD_SPEED_GEN2;
2404	else if (sata_rev == 3)
2405		val = ATA_SC_SPD_SPEED_GEN3;
2406	else
2407		val = 0;
2408	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2409	    ATA_SC_DET_RESET | val |
2410	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2411	DELAY(5000);
2412	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2413	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2414	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2415	DELAY(5000);
2416	if (!ahci_sata_connect(ch)) {
2417		if (ch->pm_level > 0)
2418			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2419		return (0);
2420	}
2421	return (1);
2422}
2423
2424static int
2425ahci_check_ids(device_t dev, union ccb *ccb)
2426{
2427	struct ahci_channel *ch = device_get_softc(dev);
2428
2429	if (ccb->ccb_h.target_id > ((ch->caps & AHCI_CAP_SPM) ? 15 : 0)) {
2430		ccb->ccb_h.status = CAM_TID_INVALID;
2431		xpt_done(ccb);
2432		return (-1);
2433	}
2434	if (ccb->ccb_h.target_lun != 0) {
2435		ccb->ccb_h.status = CAM_LUN_INVALID;
2436		xpt_done(ccb);
2437		return (-1);
2438	}
2439	return (0);
2440}
2441
2442static void
2443ahciaction(struct cam_sim *sim, union ccb *ccb)
2444{
2445	device_t dev;
2446	struct ahci_channel *ch;
2447
2448	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2449	    ccb->ccb_h.func_code));
2450
2451	ch = (struct ahci_channel *)cam_sim_softc(sim);
2452	dev = ch->dev;
2453	switch (ccb->ccb_h.func_code) {
2454	/* Common cases first */
2455	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2456	case XPT_SCSI_IO:
2457		if (ahci_check_ids(dev, ccb))
2458			return;
2459		if (ch->devices == 0 ||
2460		    (ch->pm_present == 0 &&
2461		     ccb->ccb_h.target_id > 0 && ccb->ccb_h.target_id < 15)) {
2462			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2463			break;
2464		}
2465		/* Check for command collision. */
2466		if (ahci_check_collision(dev, ccb)) {
2467			/* Freeze command. */
2468			ch->frozen = ccb;
2469			/* We have only one frozen slot, so freeze simq also. */
2470			xpt_freeze_simq(ch->sim, 1);
2471			return;
2472		}
2473		ahci_begin_transaction(dev, ccb);
2474		return;
2475	case XPT_EN_LUN:		/* Enable LUN as a target */
2476	case XPT_TARGET_IO:		/* Execute target I/O request */
2477	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2478	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2479	case XPT_ABORT:			/* Abort the specified CCB */
2480		/* XXX Implement */
2481		ccb->ccb_h.status = CAM_REQ_INVALID;
2482		break;
2483	case XPT_SET_TRAN_SETTINGS:
2484	{
2485		struct	ccb_trans_settings *cts = &ccb->cts;
2486		struct	ahci_device *d;
2487
2488		if (ahci_check_ids(dev, ccb))
2489			return;
2490		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2491			d = &ch->curr[ccb->ccb_h.target_id];
2492		else
2493			d = &ch->user[ccb->ccb_h.target_id];
2494		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2495			d->revision = cts->xport_specific.sata.revision;
2496		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2497			d->mode = cts->xport_specific.sata.mode;
2498		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2499			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2500		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2501			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2502		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2503			ch->pm_present = cts->xport_specific.sata.pm_present;
2504		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2505			d->atapi = cts->xport_specific.sata.atapi;
2506		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_CAPS)
2507			d->caps = cts->xport_specific.sata.caps;
2508		ccb->ccb_h.status = CAM_REQ_CMP;
2509		break;
2510	}
2511	case XPT_GET_TRAN_SETTINGS:
2512	/* Get default/user set transfer settings for the target */
2513	{
2514		struct	ccb_trans_settings *cts = &ccb->cts;
2515		struct  ahci_device *d;
2516		uint32_t status;
2517
2518		if (ahci_check_ids(dev, ccb))
2519			return;
2520		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2521			d = &ch->curr[ccb->ccb_h.target_id];
2522		else
2523			d = &ch->user[ccb->ccb_h.target_id];
2524		cts->protocol = PROTO_ATA;
2525		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2526		cts->transport = XPORT_SATA;
2527		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2528		cts->proto_specific.valid = 0;
2529		cts->xport_specific.sata.valid = 0;
2530		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2531		    (ccb->ccb_h.target_id == 15 ||
2532		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2533			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2534			if (status & 0x0f0) {
2535				cts->xport_specific.sata.revision =
2536				    (status & 0x0f0) >> 4;
2537				cts->xport_specific.sata.valid |=
2538				    CTS_SATA_VALID_REVISION;
2539			}
2540			cts->xport_specific.sata.caps = d->caps & CTS_SATA_CAPS_D;
2541			if (ch->pm_level) {
2542				if (ch->caps & (AHCI_CAP_PSC | AHCI_CAP_SSC))
2543					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_PMREQ;
2544				if (ch->caps2 & AHCI_CAP2_APST)
2545					cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_APST;
2546			}
2547			if ((ch->caps & AHCI_CAP_SNCQ) &&
2548			    (ch->quirks & AHCI_Q_NOAA) == 0)
2549				cts->xport_specific.sata.caps |= CTS_SATA_CAPS_H_DMAAA;
2550			cts->xport_specific.sata.caps &=
2551			    ch->user[ccb->ccb_h.target_id].caps;
2552			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2553		} else {
2554			cts->xport_specific.sata.revision = d->revision;
2555			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2556			cts->xport_specific.sata.caps = d->caps;
2557			cts->xport_specific.sata.valid |= CTS_SATA_VALID_CAPS;
2558		}
2559		cts->xport_specific.sata.mode = d->mode;
2560		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2561		cts->xport_specific.sata.bytecount = d->bytecount;
2562		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2563		cts->xport_specific.sata.pm_present = ch->pm_present;
2564		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2565		cts->xport_specific.sata.tags = d->tags;
2566		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2567		cts->xport_specific.sata.atapi = d->atapi;
2568		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2569		ccb->ccb_h.status = CAM_REQ_CMP;
2570		break;
2571	}
2572	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2573	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2574		ahci_reset(dev);
2575		ccb->ccb_h.status = CAM_REQ_CMP;
2576		break;
2577	case XPT_TERM_IO:		/* Terminate the I/O process */
2578		/* XXX Implement */
2579		ccb->ccb_h.status = CAM_REQ_INVALID;
2580		break;
2581	case XPT_PATH_INQ:		/* Path routing inquiry */
2582	{
2583		struct ccb_pathinq *cpi = &ccb->cpi;
2584
2585		cpi->version_num = 1; /* XXX??? */
2586		cpi->hba_inquiry = PI_SDTR_ABLE;
2587		if (ch->caps & AHCI_CAP_SNCQ)
2588			cpi->hba_inquiry |= PI_TAG_ABLE;
2589		if (ch->caps & AHCI_CAP_SPM)
2590			cpi->hba_inquiry |= PI_SATAPM;
2591		cpi->target_sprt = 0;
2592		cpi->hba_misc = PIM_SEQSCAN;
2593		cpi->hba_eng_cnt = 0;
2594		if (ch->caps & AHCI_CAP_SPM)
2595			cpi->max_target = 15;
2596		else
2597			cpi->max_target = 0;
2598		cpi->max_lun = 0;
2599		cpi->initiator_id = 0;
2600		cpi->bus_id = cam_sim_bus(sim);
2601		cpi->base_transfer_speed = 150000;
2602		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2603		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2604		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2605		cpi->unit_number = cam_sim_unit(sim);
2606		cpi->transport = XPORT_SATA;
2607		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2608		cpi->protocol = PROTO_ATA;
2609		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2610		cpi->maxio = MAXPHYS;
2611		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2612		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
2613			cpi->maxio = min(cpi->maxio, 128 * 512);
2614		cpi->ccb_h.status = CAM_REQ_CMP;
2615		break;
2616	}
2617	default:
2618		ccb->ccb_h.status = CAM_REQ_INVALID;
2619		break;
2620	}
2621	xpt_done(ccb);
2622}
2623
2624static void
2625ahcipoll(struct cam_sim *sim)
2626{
2627	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2628
2629	ahci_ch_intr(ch->dev);
2630}
2631