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