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