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