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