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