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