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