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