ahci_generic.c revision 203123
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 203123 2010-01-28 17:54:47Z 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 (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1171		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1172		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
1173			if (bootverbose)
1174				device_printf(dev, "CONNECT requested\n");
1175			ahci_reset(dev);
1176		} else {
1177			if (bootverbose)
1178				device_printf(dev, "DISCONNECT requested\n");
1179			ch->devices = 0;
1180		}
1181		if ((ccb = xpt_alloc_ccb_nowait()) == NULL)
1182			return;
1183		if (xpt_create_path(&ccb->ccb_h.path, NULL,
1184		    cam_sim_path(ch->sim),
1185		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1186			xpt_free_ccb(ccb);
1187			return;
1188		}
1189		xpt_rescan(ccb);
1190	}
1191}
1192
1193static void
1194ahci_notify_events(device_t dev, u_int32_t status)
1195{
1196	struct ahci_channel *ch = device_get_softc(dev);
1197	struct cam_path *dpath;
1198	int i;
1199
1200	if (ch->caps & AHCI_CAP_SSNTF)
1201		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1202	if (bootverbose)
1203		device_printf(dev, "SNTF 0x%04x\n", status);
1204	for (i = 0; i < 16; i++) {
1205		if ((status & (1 << i)) == 0)
1206			continue;
1207		if (xpt_create_path(&dpath, NULL,
1208		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1209			xpt_async(AC_SCSI_AEN, dpath, NULL);
1210			xpt_free_path(dpath);
1211		}
1212	}
1213}
1214
1215static void
1216ahci_ch_intr_locked(void *data)
1217{
1218	device_t dev = (device_t)data;
1219	struct ahci_channel *ch = device_get_softc(dev);
1220
1221	mtx_lock(&ch->mtx);
1222	ahci_ch_intr(data);
1223	mtx_unlock(&ch->mtx);
1224}
1225
1226static void
1227ahci_ch_pm(void *arg)
1228{
1229	device_t dev = (device_t)arg;
1230	struct ahci_channel *ch = device_get_softc(dev);
1231	uint32_t work;
1232
1233	if (ch->numrslots != 0)
1234		return;
1235	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1236	if (ch->pm_level == 4)
1237		work |= AHCI_P_CMD_PARTIAL;
1238	else
1239		work |= AHCI_P_CMD_SLUMBER;
1240	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1241}
1242
1243static void
1244ahci_ch_intr(void *data)
1245{
1246	device_t dev = (device_t)data;
1247	struct ahci_channel *ch = device_get_softc(dev);
1248	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1249	enum ahci_err_type et;
1250	int i, ccs, port;
1251
1252	/* Read and clear interrupt statuses. */
1253	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1254	if (istatus == 0)
1255		return;
1256	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1257	/* Read command statuses. */
1258	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1259	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1260	if (istatus & AHCI_P_IX_SDB) {
1261		if (ch->caps & AHCI_CAP_SSNTF)
1262			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1263		else if (ch->fbs_enabled) {
1264			u_int8_t *fis = ch->dma.rfis + 0x58;
1265
1266			for (i = 0; i < 16; i++) {
1267				if (fis[1] & 0x80) {
1268					fis[1] &= 0x7f;
1269	    				sntf |= 1 << i;
1270	    			}
1271	    			fis += 256;
1272	    		}
1273		} else {
1274			u_int8_t *fis = ch->dma.rfis + 0x58;
1275
1276			if (fis[1] & 0x80)
1277				sntf = (1 << (fis[1] & 0x0f));
1278		}
1279	}
1280	/* Process PHY events */
1281	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1282	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1283		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1284		if (serr) {
1285			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1286			ahci_phy_check_events(dev, serr);
1287		}
1288	}
1289	/* Process command errors */
1290	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1291	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1292		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1293		    >> AHCI_P_CMD_CCS_SHIFT;
1294//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x fbs %08x ccs %d\n",
1295//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1296//    serr, ATA_INL(ch->r_mem, AHCI_P_FBS), ccs);
1297		port = -1;
1298		if (ch->fbs_enabled) {
1299			uint32_t fbs = ATA_INL(ch->r_mem, AHCI_P_FBS);
1300			if (fbs & AHCI_P_FBS_SDE) {
1301				port = (fbs & AHCI_P_FBS_DWE)
1302				    >> AHCI_P_FBS_DWE_SHIFT;
1303			} else {
1304				for (i = 0; i < 16; i++) {
1305					if (ch->numrslotspd[i] == 0)
1306						continue;
1307					if (port == -1)
1308						port = i;
1309					else if (port != i) {
1310						port = -2;
1311						break;
1312					}
1313				}
1314			}
1315		}
1316		err = ch->rslots & (cstatus | sstatus);
1317	} else {
1318		ccs = 0;
1319		err = 0;
1320		port = -1;
1321	}
1322	/* Complete all successfull commands. */
1323	ok = ch->rslots & ~(cstatus | sstatus);
1324	for (i = 0; i < ch->numslots; i++) {
1325		if ((ok >> i) & 1)
1326			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1327	}
1328	/* On error, complete the rest of commands with error statuses. */
1329	if (err) {
1330		if (ch->frozen) {
1331			union ccb *fccb = ch->frozen;
1332			ch->frozen = NULL;
1333			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1334			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1335				xpt_freeze_devq(fccb->ccb_h.path, 1);
1336				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1337			}
1338			xpt_done(fccb);
1339		}
1340		for (i = 0; i < ch->numslots; i++) {
1341			/* XXX: reqests in loading state. */
1342			if (((err >> i) & 1) == 0)
1343				continue;
1344			if (port >= 0 &&
1345			    ch->slot[i].ccb->ccb_h.target_id != port)
1346				continue;
1347			if (istatus & AHCI_P_IX_TFE) {
1348			    if (port != -2) {
1349				/* Task File Error */
1350				if (ch->numtslotspd[
1351				    ch->slot[i].ccb->ccb_h.target_id] == 0) {
1352					/* Untagged operation. */
1353					if (i == ccs)
1354						et = AHCI_ERR_TFE;
1355					else
1356						et = AHCI_ERR_INNOCENT;
1357				} else {
1358					/* Tagged operation. */
1359					et = AHCI_ERR_NCQ;
1360				}
1361			    } else {
1362				et = AHCI_ERR_TFE;
1363				ch->fatalerr = 1;
1364			    }
1365			} else if (istatus & AHCI_P_IX_IF) {
1366				if (ch->numtslots == 0 && i != ccs && port != -2)
1367					et = AHCI_ERR_INNOCENT;
1368				else
1369					et = AHCI_ERR_SATA;
1370			} else
1371				et = AHCI_ERR_INVALID;
1372			ahci_end_transaction(&ch->slot[i], et);
1373		}
1374		/*
1375		 * We can't reinit port if there are some other
1376		 * commands active, use resume to complete them.
1377		 */
1378		if (ch->rslots != 0)
1379			ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN | AHCI_P_FBS_DEC);
1380	}
1381	/* Process NOTIFY events */
1382	if (sntf)
1383		ahci_notify_events(dev, sntf);
1384}
1385
1386/* Must be called with channel locked. */
1387static int
1388ahci_check_collision(device_t dev, union ccb *ccb)
1389{
1390	struct ahci_channel *ch = device_get_softc(dev);
1391	int t = ccb->ccb_h.target_id;
1392
1393	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1394	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1395		/* Tagged command while we have no supported tag free. */
1396		if (((~ch->oslots) & (0xffffffff >> (32 -
1397		    ch->curr[t].tags))) == 0)
1398			return (1);
1399		/* If we have FBS */
1400		if (ch->fbs_enabled) {
1401			/* Tagged command while untagged are active. */
1402			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] == 0)
1403				return (1);
1404		} else {
1405			/* Tagged command while untagged are active. */
1406			if (ch->numrslots != 0 && ch->numtslots == 0)
1407				return (1);
1408			/* Tagged command while tagged to other target is active. */
1409			if (ch->numtslots != 0 &&
1410			    ch->taggedtarget != ccb->ccb_h.target_id)
1411				return (1);
1412		}
1413	} else {
1414		/* If we have FBS */
1415		if (ch->fbs_enabled) {
1416			/* Untagged command while tagged are active. */
1417			if (ch->numrslotspd[t] != 0 && ch->numtslotspd[t] != 0)
1418				return (1);
1419		} else {
1420			/* Untagged command while tagged are active. */
1421			if (ch->numrslots != 0 && ch->numtslots != 0)
1422				return (1);
1423		}
1424	}
1425	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1426	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1427		/* Atomic command while anything active. */
1428		if (ch->numrslots != 0)
1429			return (1);
1430	}
1431       /* We have some atomic command running. */
1432       if (ch->aslots != 0)
1433               return (1);
1434	return (0);
1435}
1436
1437/* Must be called with channel locked. */
1438static void
1439ahci_begin_transaction(device_t dev, union ccb *ccb)
1440{
1441	struct ahci_channel *ch = device_get_softc(dev);
1442	struct ahci_slot *slot;
1443	int tag, tags;
1444
1445	/* Choose empty slot. */
1446	tags = ch->numslots;
1447	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1448	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1449		tags = ch->curr[ccb->ccb_h.target_id].tags;
1450	tag = ch->lastslot;
1451	while (1) {
1452		if (tag >= tags)
1453			tag = 0;
1454		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1455			break;
1456		tag++;
1457	};
1458	ch->lastslot = tag;
1459	/* Occupy chosen slot. */
1460	slot = &ch->slot[tag];
1461	slot->ccb = ccb;
1462	/* Stop PM timer. */
1463	if (ch->numrslots == 0 && ch->pm_level > 3)
1464		callout_stop(&ch->pm_timer);
1465	/* Update channel stats. */
1466	ch->oslots |= (1 << slot->slot);
1467	ch->numrslots++;
1468	ch->numrslotspd[ccb->ccb_h.target_id]++;
1469	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1470	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1471		ch->numtslots++;
1472		ch->numtslotspd[ccb->ccb_h.target_id]++;
1473		ch->taggedtarget = ccb->ccb_h.target_id;
1474	}
1475	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1476	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1477		ch->aslots |= (1 << slot->slot);
1478	slot->dma.nsegs = 0;
1479	/* If request moves data, setup and load SG list */
1480	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1481		void *buf;
1482		bus_size_t size;
1483
1484		slot->state = AHCI_SLOT_LOADING;
1485		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1486			buf = ccb->ataio.data_ptr;
1487			size = ccb->ataio.dxfer_len;
1488		} else {
1489			buf = ccb->csio.data_ptr;
1490			size = ccb->csio.dxfer_len;
1491		}
1492		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1493		    buf, size, ahci_dmasetprd, slot, 0);
1494	} else
1495		ahci_execute_transaction(slot);
1496}
1497
1498/* Locked by busdma engine. */
1499static void
1500ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1501{
1502	struct ahci_slot *slot = arg;
1503	struct ahci_channel *ch = device_get_softc(slot->dev);
1504	struct ahci_cmd_tab *ctp;
1505	struct ahci_dma_prd *prd;
1506	int i;
1507
1508	if (error) {
1509		device_printf(slot->dev, "DMA load error\n");
1510		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1511		return;
1512	}
1513	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1514	/* Get a piece of the workspace for this request */
1515	ctp = (struct ahci_cmd_tab *)
1516		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1517	/* Fill S/G table */
1518	prd = &ctp->prd_tab[0];
1519	for (i = 0; i < nsegs; i++) {
1520		prd[i].dba = htole64(segs[i].ds_addr);
1521		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1522	}
1523	slot->dma.nsegs = nsegs;
1524	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1525	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1526	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1527	ahci_execute_transaction(slot);
1528}
1529
1530/* Must be called with channel locked. */
1531static void
1532ahci_execute_transaction(struct ahci_slot *slot)
1533{
1534	device_t dev = slot->dev;
1535	struct ahci_channel *ch = device_get_softc(dev);
1536	struct ahci_cmd_tab *ctp;
1537	struct ahci_cmd_list *clp;
1538	union ccb *ccb = slot->ccb;
1539	int port = ccb->ccb_h.target_id & 0x0f;
1540	int fis_size, i;
1541	uint8_t *fis = ch->dma.rfis + 0x40;
1542	uint8_t val;
1543
1544	/* Get a piece of the workspace for this request */
1545	ctp = (struct ahci_cmd_tab *)
1546		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1547	/* Setup the FIS for this request */
1548	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1549		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1550		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1551		return;
1552	}
1553	/* Setup the command list entry */
1554	clp = (struct ahci_cmd_list *)
1555	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1556	clp->prd_length = slot->dma.nsegs;
1557	clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1558		     (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1559		      (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1560		     (fis_size / sizeof(u_int32_t)) |
1561		     (port << 12);
1562	/* Special handling for Soft Reset command. */
1563	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1564	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL)) {
1565		if (ccb->ataio.cmd.control & ATA_A_RESET) {
1566			/* Kick controller into sane state */
1567			ahci_stop(dev);
1568			ahci_clo(dev);
1569			ahci_start(dev, 0);
1570			clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1571		} else {
1572			/* Prepare FIS receive area for check. */
1573			for (i = 0; i < 20; i++)
1574				fis[i] = 0xff;
1575		}
1576	}
1577	clp->bytecount = 0;
1578	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1579				  (AHCI_CT_SIZE * slot->slot));
1580	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1581	    BUS_DMASYNC_PREWRITE);
1582	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1583	    BUS_DMASYNC_PREREAD);
1584	/* Set ACTIVE bit for NCQ commands. */
1585	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1586	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1587		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1588	}
1589	/* If FBS is enabled, set PMP port. */
1590	if (ch->fbs_enabled) {
1591		ATA_OUTL(ch->r_mem, AHCI_P_FBS, AHCI_P_FBS_EN |
1592		    (port << AHCI_P_FBS_DEV_SHIFT));
1593	}
1594	/* Issue command to the controller. */
1595	slot->state = AHCI_SLOT_RUNNING;
1596	ch->rslots |= (1 << slot->slot);
1597	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1598	/* Device reset commands doesn't interrupt. Poll them. */
1599	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1600	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1601	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1602		int count, timeout = ccb->ccb_h.timeout;
1603		enum ahci_err_type et = AHCI_ERR_NONE;
1604
1605		for (count = 0; count < timeout; count++) {
1606			DELAY(1000);
1607			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1608				break;
1609			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1610				device_printf(ch->dev,
1611				    "Poll error on slot %d, TFD: %04x\n",
1612				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1613				et = AHCI_ERR_TFE;
1614				break;
1615			}
1616			/* Workaround for ATI SB600/SB700 chipsets. */
1617			if (ccb->ccb_h.target_id == 15 &&
1618			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1619			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1620				et = AHCI_ERR_TIMEOUT;
1621				break;
1622			}
1623		}
1624		if (timeout && (count >= timeout)) {
1625			device_printf(ch->dev,
1626			    "Poll timeout on slot %d\n", slot->slot);
1627			device_printf(dev, "is %08x cs %08x ss %08x "
1628			    "rs %08x tfd %02x serr %08x\n",
1629			    ATA_INL(ch->r_mem, AHCI_P_IS),
1630			    ATA_INL(ch->r_mem, AHCI_P_CI),
1631			    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1632			    ATA_INL(ch->r_mem, AHCI_P_TFD),
1633			    ATA_INL(ch->r_mem, AHCI_P_SERR));
1634			et = AHCI_ERR_TIMEOUT;
1635		}
1636		/* Marvell controllers do not wait for readyness. */
1637		if ((ch->quirks & AHCI_Q_NOBSYRES) &&
1638		    (ccb->ccb_h.func_code == XPT_ATA_IO) &&
1639		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1640		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1641			while ((val = fis[2]) & (ATA_S_BUSY | ATA_S_DRQ)) {
1642				DELAY(1000);
1643				if (count++ >= timeout) {
1644					device_printf(dev, "device is not "
1645					    "ready after soft-reset: "
1646					    "tfd = %08x\n", val);
1647	    				et = AHCI_ERR_TIMEOUT;
1648	    				break;
1649				}
1650			}
1651		}
1652		ahci_end_transaction(slot, et);
1653		/* Kick controller into sane state and enable FBS. */
1654		if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1655		    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1656		    (ccb->ataio.cmd.control & ATA_A_RESET) == 0) {
1657			ahci_stop(ch->dev);
1658			ahci_start(ch->dev, 1);
1659		}
1660		return;
1661	}
1662	/* Start command execution timeout */
1663	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1664	    (timeout_t*)ahci_timeout, slot);
1665	return;
1666}
1667
1668/* Locked by callout mechanism. */
1669static void
1670ahci_timeout(struct ahci_slot *slot)
1671{
1672	device_t dev = slot->dev;
1673	struct ahci_channel *ch = device_get_softc(dev);
1674	uint32_t sstatus;
1675	int ccs;
1676	int i;
1677
1678	/* Check for stale timeout. */
1679	if (slot->state < AHCI_SLOT_RUNNING)
1680		return;
1681
1682	/* Check if slot was not being executed last time we checked. */
1683	if (slot->state < AHCI_SLOT_EXECUTING) {
1684		/* Check if slot started executing. */
1685		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1686		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1687		    >> AHCI_P_CMD_CCS_SHIFT;
1688		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1689		    ch->fbs_enabled)
1690			slot->state = AHCI_SLOT_EXECUTING;
1691
1692		callout_reset(&slot->timeout,
1693		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1694		    (timeout_t*)ahci_timeout, slot);
1695		return;
1696	}
1697
1698	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1699	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1700	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1701	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1702	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1703
1704	ch->fatalerr = 1;
1705	/* Handle frozen command. */
1706	if (ch->frozen) {
1707		union ccb *fccb = ch->frozen;
1708		ch->frozen = NULL;
1709		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1710		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1711			xpt_freeze_devq(fccb->ccb_h.path, 1);
1712			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1713		}
1714		xpt_done(fccb);
1715	}
1716	/* Handle command with timeout. */
1717	ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1718	/* Handle the rest of commands. */
1719	for (i = 0; i < ch->numslots; i++) {
1720		/* Do we have a running request on slot? */
1721		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1722			continue;
1723		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1724	}
1725}
1726
1727/* Must be called with channel locked. */
1728static void
1729ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1730{
1731	device_t dev = slot->dev;
1732	struct ahci_channel *ch = device_get_softc(dev);
1733	union ccb *ccb = slot->ccb;
1734
1735	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1736	    BUS_DMASYNC_POSTWRITE);
1737	/* Read result registers to the result struct
1738	 * May be incorrect if several commands finished same time,
1739	 * so read only when sure or have to.
1740	 */
1741	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1742		struct ata_res *res = &ccb->ataio.res;
1743
1744		if ((et == AHCI_ERR_TFE) ||
1745		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1746			u_int8_t *fis = ch->dma.rfis + 0x40;
1747
1748			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1749			    BUS_DMASYNC_POSTREAD);
1750			if (ch->fbs_enabled) {
1751				fis += ccb->ccb_h.target_id * 256;
1752				res->status = fis[2];
1753				res->error = fis[3];
1754			} else {
1755				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1756
1757				res->status = tfd;
1758				res->error = tfd >> 8;
1759			}
1760			res->lba_low = fis[4];
1761			res->lba_mid = fis[5];
1762			res->lba_high = fis[6];
1763			res->device = fis[7];
1764			res->lba_low_exp = fis[8];
1765			res->lba_mid_exp = fis[9];
1766			res->lba_high_exp = fis[10];
1767			res->sector_count = fis[12];
1768			res->sector_count_exp = fis[13];
1769		} else
1770			bzero(res, sizeof(*res));
1771	}
1772	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1773		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1774		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1775		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1776		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1777	}
1778	if (et != AHCI_ERR_NONE)
1779		ch->eslots |= (1 << slot->slot);
1780	/* In case of error, freeze device for proper recovery. */
1781	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1782	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1783		xpt_freeze_devq(ccb->ccb_h.path, 1);
1784		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1785	}
1786	/* Set proper result status. */
1787	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1788	switch (et) {
1789	case AHCI_ERR_NONE:
1790		ccb->ccb_h.status |= CAM_REQ_CMP;
1791		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1792			ccb->csio.scsi_status = SCSI_STATUS_OK;
1793		break;
1794	case AHCI_ERR_INVALID:
1795		ch->fatalerr = 1;
1796		ccb->ccb_h.status |= CAM_REQ_INVALID;
1797		break;
1798	case AHCI_ERR_INNOCENT:
1799		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1800		break;
1801	case AHCI_ERR_TFE:
1802	case AHCI_ERR_NCQ:
1803		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1804			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1805			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1806		} else {
1807			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1808		}
1809		break;
1810	case AHCI_ERR_SATA:
1811		ch->fatalerr = 1;
1812		if (!ch->readlog) {
1813			xpt_freeze_simq(ch->sim, 1);
1814			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1815			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1816		}
1817		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1818		break;
1819	case AHCI_ERR_TIMEOUT:
1820		/* Do no treat soft-reset timeout as fatal here. */
1821		if (ccb->ccb_h.func_code != XPT_ATA_IO ||
1822	            !(ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))
1823			ch->fatalerr = 1;
1824		if (!ch->readlog) {
1825			xpt_freeze_simq(ch->sim, 1);
1826			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1827			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1828		}
1829		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1830		break;
1831	default:
1832		ch->fatalerr = 1;
1833		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1834	}
1835	/* Free slot. */
1836	ch->oslots &= ~(1 << slot->slot);
1837	ch->rslots &= ~(1 << slot->slot);
1838	ch->aslots &= ~(1 << slot->slot);
1839	slot->state = AHCI_SLOT_EMPTY;
1840	slot->ccb = NULL;
1841	/* Update channel stats. */
1842	ch->numrslots--;
1843	ch->numrslotspd[ccb->ccb_h.target_id]--;
1844	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1845	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1846		ch->numtslots--;
1847		ch->numtslotspd[ccb->ccb_h.target_id]--;
1848	}
1849	/* If it was first request of reset sequence and there is no error,
1850	 * proceed to second request. */
1851	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1852	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1853	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1854	    et == AHCI_ERR_NONE) {
1855		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1856		ahci_begin_transaction(dev, ccb);
1857		return;
1858	}
1859	/* If it was our READ LOG command - process it. */
1860	if (ch->readlog) {
1861		ahci_process_read_log(dev, ccb);
1862	/* If it was NCQ command error, put result on hold. */
1863	} else if (et == AHCI_ERR_NCQ) {
1864		ch->hold[slot->slot] = ccb;
1865		ch->numhslots++;
1866	} else
1867		xpt_done(ccb);
1868	/* Unfreeze frozen command. */
1869	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
1870		union ccb *fccb = ch->frozen;
1871		ch->frozen = NULL;
1872		ahci_begin_transaction(dev, fccb);
1873		xpt_release_simq(ch->sim, TRUE);
1874	}
1875	/* If we have no other active commands, ... */
1876	if (ch->rslots == 0) {
1877		/* if there was fatal error - reset port. */
1878		if (ch->fatalerr) {
1879			ahci_reset(dev);
1880		} else {
1881			/* if we have slots in error, we can reinit port. */
1882			if (ch->eslots != 0) {
1883				ahci_stop(dev);
1884				ahci_start(dev, 1);
1885			}
1886			/* if there commands on hold, we can do READ LOG. */
1887			if (!ch->readlog && ch->numhslots)
1888				ahci_issue_read_log(dev);
1889		}
1890	}
1891	/* Start PM timer. */
1892	if (ch->numrslots == 0 && ch->pm_level > 3) {
1893		callout_schedule(&ch->pm_timer,
1894		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1895	}
1896}
1897
1898static void
1899ahci_issue_read_log(device_t dev)
1900{
1901	struct ahci_channel *ch = device_get_softc(dev);
1902	union ccb *ccb;
1903	struct ccb_ataio *ataio;
1904	int i;
1905
1906	ch->readlog = 1;
1907	/* Find some holden command. */
1908	for (i = 0; i < ch->numslots; i++) {
1909		if (ch->hold[i])
1910			break;
1911	}
1912	ccb = xpt_alloc_ccb_nowait();
1913	if (ccb == NULL) {
1914		device_printf(dev, "Unable allocate READ LOG command");
1915		return; /* XXX */
1916	}
1917	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1918	ccb->ccb_h.func_code = XPT_ATA_IO;
1919	ccb->ccb_h.flags = CAM_DIR_IN;
1920	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1921	ataio = &ccb->ataio;
1922	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1923	if (ataio->data_ptr == NULL) {
1924		device_printf(dev, "Unable allocate memory for READ LOG command");
1925		return; /* XXX */
1926	}
1927	ataio->dxfer_len = 512;
1928	bzero(&ataio->cmd, sizeof(ataio->cmd));
1929	ataio->cmd.flags = CAM_ATAIO_48BIT;
1930	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1931	ataio->cmd.sector_count = 1;
1932	ataio->cmd.sector_count_exp = 0;
1933	ataio->cmd.lba_low = 0x10;
1934	ataio->cmd.lba_mid = 0;
1935	ataio->cmd.lba_mid_exp = 0;
1936	/* Freeze SIM while doing READ LOG EXT. */
1937	xpt_freeze_simq(ch->sim, 1);
1938	ahci_begin_transaction(dev, ccb);
1939}
1940
1941static void
1942ahci_process_read_log(device_t dev, union ccb *ccb)
1943{
1944	struct ahci_channel *ch = device_get_softc(dev);
1945	uint8_t *data;
1946	struct ata_res *res;
1947	int i;
1948
1949	ch->readlog = 0;
1950
1951	data = ccb->ataio.data_ptr;
1952	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1953	    (data[0] & 0x80) == 0) {
1954		for (i = 0; i < ch->numslots; i++) {
1955			if (!ch->hold[i])
1956				continue;
1957			if ((data[0] & 0x1F) == i) {
1958				res = &ch->hold[i]->ataio.res;
1959				res->status = data[2];
1960				res->error = data[3];
1961				res->lba_low = data[4];
1962				res->lba_mid = data[5];
1963				res->lba_high = data[6];
1964				res->device = data[7];
1965				res->lba_low_exp = data[8];
1966				res->lba_mid_exp = data[9];
1967				res->lba_high_exp = data[10];
1968				res->sector_count = data[12];
1969				res->sector_count_exp = data[13];
1970			} else {
1971				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1972				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1973			}
1974			xpt_done(ch->hold[i]);
1975			ch->hold[i] = NULL;
1976			ch->numhslots--;
1977		}
1978	} else {
1979		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1980			device_printf(dev, "Error while READ LOG EXT\n");
1981		else if ((data[0] & 0x80) == 0) {
1982			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1983		}
1984		for (i = 0; i < ch->numslots; i++) {
1985			if (!ch->hold[i])
1986				continue;
1987			xpt_done(ch->hold[i]);
1988			ch->hold[i] = NULL;
1989			ch->numhslots--;
1990		}
1991	}
1992	free(ccb->ataio.data_ptr, M_AHCI);
1993	xpt_free_ccb(ccb);
1994	xpt_release_simq(ch->sim, TRUE);
1995}
1996
1997static void
1998ahci_start(device_t dev, int fbs)
1999{
2000	struct ahci_channel *ch = device_get_softc(dev);
2001	u_int32_t cmd;
2002
2003	/* Clear SATA error register */
2004	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2005	/* Clear any interrupts pending on this channel */
2006	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2007	/* Configure FIS-based switching if supported. */
2008	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2009		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2010		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2011		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2012	}
2013	/* Start operations on this channel */
2014	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2015	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2016	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2017}
2018
2019static void
2020ahci_stop(device_t dev)
2021{
2022	struct ahci_channel *ch = device_get_softc(dev);
2023	u_int32_t cmd;
2024	int timeout;
2025
2026	/* Kill all activity on this channel */
2027	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2028	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2029	/* Wait for activity stop. */
2030	timeout = 0;
2031	do {
2032		DELAY(1000);
2033		if (timeout++ > 1000) {
2034			device_printf(dev, "stopping AHCI engine failed\n");
2035			break;
2036		}
2037	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2038	ch->eslots = 0;
2039}
2040
2041static void
2042ahci_clo(device_t dev)
2043{
2044	struct ahci_channel *ch = device_get_softc(dev);
2045	u_int32_t cmd;
2046	int timeout;
2047
2048	/* Issue Command List Override if supported */
2049	if (ch->caps & AHCI_CAP_SCLO) {
2050		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2051		cmd |= AHCI_P_CMD_CLO;
2052		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2053		timeout = 0;
2054		do {
2055			DELAY(1000);
2056			if (timeout++ > 1000) {
2057			    device_printf(dev, "executing CLO failed\n");
2058			    break;
2059			}
2060		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2061	}
2062}
2063
2064static void
2065ahci_stop_fr(device_t dev)
2066{
2067	struct ahci_channel *ch = device_get_softc(dev);
2068	u_int32_t cmd;
2069	int timeout;
2070
2071	/* Kill all FIS reception on this channel */
2072	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2073	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2074	/* Wait for FIS reception stop. */
2075	timeout = 0;
2076	do {
2077		DELAY(1000);
2078		if (timeout++ > 1000) {
2079			device_printf(dev, "stopping AHCI FR engine failed\n");
2080			break;
2081		}
2082	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2083}
2084
2085static void
2086ahci_start_fr(device_t dev)
2087{
2088	struct ahci_channel *ch = device_get_softc(dev);
2089	u_int32_t cmd;
2090
2091	/* Start FIS reception on this channel */
2092	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2093	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2094}
2095
2096static int
2097ahci_wait_ready(device_t dev, int t)
2098{
2099	struct ahci_channel *ch = device_get_softc(dev);
2100	int timeout = 0;
2101	uint32_t val;
2102
2103	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2104	    (ATA_S_BUSY | ATA_S_DRQ)) {
2105		DELAY(1000);
2106		if (timeout++ > t) {
2107			device_printf(dev, "device is not ready (timeout %dms) "
2108			    "tfd = %08x\n", t, val);
2109			return (EBUSY);
2110		}
2111	}
2112	if (bootverbose)
2113		device_printf(dev, "ready wait time=%dms\n", timeout);
2114	return (0);
2115}
2116
2117static void
2118ahci_reset(device_t dev)
2119{
2120	struct ahci_channel *ch = device_get_softc(dev);
2121	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2122	int i;
2123
2124	xpt_freeze_simq(ch->sim, 1);
2125	if (bootverbose)
2126		device_printf(dev, "AHCI reset...\n");
2127	/* Requeue freezed command. */
2128	if (ch->frozen) {
2129		union ccb *fccb = ch->frozen;
2130		ch->frozen = NULL;
2131		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2132		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2133			xpt_freeze_devq(fccb->ccb_h.path, 1);
2134			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2135		}
2136		xpt_done(fccb);
2137	}
2138	/* Kill the engine and requeue all running commands. */
2139	ahci_stop(dev);
2140	for (i = 0; i < ch->numslots; i++) {
2141		/* Do we have a running request on slot? */
2142		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2143			continue;
2144		/* XXX; Commands in loading state. */
2145		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2146	}
2147	for (i = 0; i < ch->numslots; i++) {
2148		if (!ch->hold[i])
2149			continue;
2150		xpt_done(ch->hold[i]);
2151		ch->hold[i] = NULL;
2152		ch->numhslots--;
2153	}
2154	ch->eslots = 0;
2155	ch->fatalerr = 0;
2156	/* Tell the XPT about the event */
2157	xpt_async(AC_BUS_RESET, ch->path, NULL);
2158	/* Disable port interrupts */
2159	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2160	/* Reset and reconnect PHY, */
2161	if (!ahci_sata_phy_reset(dev)) {
2162		if (bootverbose)
2163			device_printf(dev,
2164			    "AHCI reset done: phy reset found no device\n");
2165		ch->devices = 0;
2166		/* Enable wanted port interrupts */
2167		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2168		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
2169		xpt_release_simq(ch->sim, TRUE);
2170		return;
2171	}
2172	/* Wait for clearing busy status. */
2173	if (ahci_wait_ready(dev, 15000))
2174		ahci_clo(dev);
2175	ahci_start(dev, 1);
2176	ch->devices = 1;
2177	/* Enable wanted port interrupts */
2178	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2179	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2180	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2181	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
2182	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2183	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2184	if (bootverbose)
2185		device_printf(dev, "AHCI reset done: device found\n");
2186	xpt_release_simq(ch->sim, TRUE);
2187}
2188
2189static int
2190ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2191{
2192	struct ahci_channel *ch = device_get_softc(dev);
2193	u_int8_t *fis = &ctp->cfis[0];
2194
2195	bzero(ctp->cfis, 64);
2196	fis[0] = 0x27;  		/* host to device */
2197	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2198	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2199		fis[1] |= 0x80;
2200		fis[2] = ATA_PACKET_CMD;
2201		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2202		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2203			fis[3] = ATA_F_DMA;
2204		else {
2205			fis[5] = ccb->csio.dxfer_len;
2206		        fis[6] = ccb->csio.dxfer_len >> 8;
2207		}
2208		fis[7] = ATA_D_LBA;
2209		fis[15] = ATA_A_4BIT;
2210		bzero(ctp->acmd, 32);
2211		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2212		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2213		    ctp->acmd, ccb->csio.cdb_len);
2214	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2215		fis[1] |= 0x80;
2216		fis[2] = ccb->ataio.cmd.command;
2217		fis[3] = ccb->ataio.cmd.features;
2218		fis[4] = ccb->ataio.cmd.lba_low;
2219		fis[5] = ccb->ataio.cmd.lba_mid;
2220		fis[6] = ccb->ataio.cmd.lba_high;
2221		fis[7] = ccb->ataio.cmd.device;
2222		fis[8] = ccb->ataio.cmd.lba_low_exp;
2223		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2224		fis[10] = ccb->ataio.cmd.lba_high_exp;
2225		fis[11] = ccb->ataio.cmd.features_exp;
2226		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2227			fis[12] = tag << 3;
2228			fis[13] = 0;
2229		} else {
2230			fis[12] = ccb->ataio.cmd.sector_count;
2231			fis[13] = ccb->ataio.cmd.sector_count_exp;
2232		}
2233		fis[15] = ATA_A_4BIT;
2234	} else {
2235		fis[15] = ccb->ataio.cmd.control;
2236	}
2237	return (20);
2238}
2239
2240static int
2241ahci_sata_connect(struct ahci_channel *ch)
2242{
2243	u_int32_t status;
2244	int timeout;
2245
2246	/* Wait up to 100ms for "connect well" */
2247	for (timeout = 0; timeout < 100 ; timeout++) {
2248		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2249		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2250		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2251		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2252			break;
2253		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2254			if (bootverbose) {
2255				device_printf(ch->dev, "SATA offline status=%08x\n",
2256				    status);
2257			}
2258			return (0);
2259		}
2260		DELAY(1000);
2261	}
2262	if (timeout >= 100) {
2263		if (bootverbose) {
2264			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2265			    status);
2266		}
2267		return (0);
2268	}
2269	if (bootverbose) {
2270		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2271		    timeout, status);
2272	}
2273	/* Clear SATA error register */
2274	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2275	return (1);
2276}
2277
2278static int
2279ahci_sata_phy_reset(device_t dev)
2280{
2281	struct ahci_channel *ch = device_get_softc(dev);
2282	int sata_rev;
2283	uint32_t val;
2284
2285	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2286	if (sata_rev == 1)
2287		val = ATA_SC_SPD_SPEED_GEN1;
2288	else if (sata_rev == 2)
2289		val = ATA_SC_SPD_SPEED_GEN2;
2290	else if (sata_rev == 3)
2291		val = ATA_SC_SPD_SPEED_GEN3;
2292	else
2293		val = 0;
2294	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2295	    ATA_SC_DET_RESET | val |
2296	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2297	DELAY(5000);
2298	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2299	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2300	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2301	DELAY(5000);
2302	return (ahci_sata_connect(ch));
2303}
2304
2305static void
2306ahciaction(struct cam_sim *sim, union ccb *ccb)
2307{
2308	device_t dev;
2309	struct ahci_channel *ch;
2310
2311	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2312	    ccb->ccb_h.func_code));
2313
2314	ch = (struct ahci_channel *)cam_sim_softc(sim);
2315	dev = ch->dev;
2316	switch (ccb->ccb_h.func_code) {
2317	/* Common cases first */
2318	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2319	case XPT_SCSI_IO:
2320		if (ch->devices == 0) {
2321			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2322			xpt_done(ccb);
2323			break;
2324		}
2325		/* Check for command collision. */
2326		if (ahci_check_collision(dev, ccb)) {
2327			/* Freeze command. */
2328			ch->frozen = ccb;
2329			/* We have only one frozen slot, so freeze simq also. */
2330			xpt_freeze_simq(ch->sim, 1);
2331			return;
2332		}
2333		ahci_begin_transaction(dev, ccb);
2334		break;
2335	case XPT_EN_LUN:		/* Enable LUN as a target */
2336	case XPT_TARGET_IO:		/* Execute target I/O request */
2337	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2338	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2339	case XPT_ABORT:			/* Abort the specified CCB */
2340		/* XXX Implement */
2341		ccb->ccb_h.status = CAM_REQ_INVALID;
2342		xpt_done(ccb);
2343		break;
2344	case XPT_SET_TRAN_SETTINGS:
2345	{
2346		struct	ccb_trans_settings *cts = &ccb->cts;
2347		struct	ahci_device *d;
2348
2349		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2350			d = &ch->curr[ccb->ccb_h.target_id];
2351		else
2352			d = &ch->user[ccb->ccb_h.target_id];
2353		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2354			d->revision = cts->xport_specific.sata.revision;
2355		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2356			d->mode = cts->xport_specific.sata.mode;
2357		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2358			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2359		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2360			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2361		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2362			ch->pm_present = cts->xport_specific.sata.pm_present;
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		ccb->ccb_h.status = CAM_REQ_CMP;
2407		xpt_done(ccb);
2408		break;
2409	}
2410#if 0
2411	case XPT_CALC_GEOMETRY:
2412	{
2413		struct	  ccb_calc_geometry *ccg;
2414		uint32_t size_mb;
2415		uint32_t secs_per_cylinder;
2416
2417		ccg = &ccb->ccg;
2418		size_mb = ccg->volume_size
2419			/ ((1024L * 1024L) / ccg->block_size);
2420		if (size_mb >= 1024 && (aha->extended_trans != 0)) {
2421			if (size_mb >= 2048) {
2422				ccg->heads = 255;
2423				ccg->secs_per_track = 63;
2424			} else {
2425				ccg->heads = 128;
2426				ccg->secs_per_track = 32;
2427			}
2428		} else {
2429			ccg->heads = 64;
2430			ccg->secs_per_track = 32;
2431		}
2432		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2433		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2434		ccb->ccb_h.status = CAM_REQ_CMP;
2435		xpt_done(ccb);
2436		break;
2437	}
2438#endif
2439	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2440	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2441		ahci_reset(dev);
2442		ccb->ccb_h.status = CAM_REQ_CMP;
2443		xpt_done(ccb);
2444		break;
2445	case XPT_TERM_IO:		/* Terminate the I/O process */
2446		/* XXX Implement */
2447		ccb->ccb_h.status = CAM_REQ_INVALID;
2448		xpt_done(ccb);
2449		break;
2450	case XPT_PATH_INQ:		/* Path routing inquiry */
2451	{
2452		struct ccb_pathinq *cpi = &ccb->cpi;
2453
2454		cpi->version_num = 1; /* XXX??? */
2455		cpi->hba_inquiry = PI_SDTR_ABLE;
2456		if (ch->caps & AHCI_CAP_SNCQ)
2457			cpi->hba_inquiry |= PI_TAG_ABLE;
2458		if (ch->caps & AHCI_CAP_SPM)
2459			cpi->hba_inquiry |= PI_SATAPM;
2460		cpi->target_sprt = 0;
2461		cpi->hba_misc = PIM_SEQSCAN;
2462		cpi->hba_eng_cnt = 0;
2463		if (ch->caps & AHCI_CAP_SPM)
2464			cpi->max_target = 15;
2465		else
2466			cpi->max_target = 0;
2467		cpi->max_lun = 0;
2468		cpi->initiator_id = 0;
2469		cpi->bus_id = cam_sim_bus(sim);
2470		cpi->base_transfer_speed = 150000;
2471		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2472		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2473		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2474		cpi->unit_number = cam_sim_unit(sim);
2475		cpi->transport = XPORT_SATA;
2476		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2477		cpi->protocol = PROTO_ATA;
2478		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2479		cpi->maxio = MAXPHYS;
2480		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2481		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
2482			cpi->maxio = min(cpi->maxio, 128 * 512);
2483		cpi->ccb_h.status = CAM_REQ_CMP;
2484		xpt_done(ccb);
2485		break;
2486	}
2487	default:
2488		ccb->ccb_h.status = CAM_REQ_INVALID;
2489		xpt_done(ccb);
2490		break;
2491	}
2492}
2493
2494static void
2495ahcipoll(struct cam_sim *sim)
2496{
2497	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2498
2499	ahci_ch_intr(ch->dev);
2500}
2501