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