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