ahci_generic.c revision 203873
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 203873 2010-02-14 12:30:35Z 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/* Must be called with channel locked. */
1667static void
1668ahci_process_timeout(device_t dev)
1669{
1670	struct ahci_channel *ch = device_get_softc(dev);
1671	int i;
1672
1673	mtx_assert(&ch->mtx, MA_OWNED);
1674	/* Handle the rest of commands. */
1675	for (i = 0; i < ch->numslots; i++) {
1676		/* Do we have a running request on slot? */
1677		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1678			continue;
1679		ahci_end_transaction(&ch->slot[i], AHCI_ERR_TIMEOUT);
1680	}
1681}
1682
1683/* Must be called with channel locked. */
1684static void
1685ahci_rearm_timeout(device_t dev)
1686{
1687	struct ahci_channel *ch = device_get_softc(dev);
1688	int i;
1689
1690	mtx_assert(&ch->mtx, MA_OWNED);
1691	for (i = 0; i < ch->numslots; i++) {
1692		struct ahci_slot *slot = &ch->slot[i];
1693
1694		/* Do we have a running request on slot? */
1695		if (slot->state < AHCI_SLOT_RUNNING)
1696			continue;
1697		if ((ch->toslots & (1 << i)) == 0)
1698			continue;
1699		callout_reset(&slot->timeout,
1700		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1701		    (timeout_t*)ahci_timeout, slot);
1702	}
1703}
1704
1705/* Locked by callout mechanism. */
1706static void
1707ahci_timeout(struct ahci_slot *slot)
1708{
1709	device_t dev = slot->dev;
1710	struct ahci_channel *ch = device_get_softc(dev);
1711	uint32_t sstatus;
1712	int ccs;
1713	int i;
1714
1715	/* Check for stale timeout. */
1716	if (slot->state < AHCI_SLOT_RUNNING)
1717		return;
1718
1719	/* Check if slot was not being executed last time we checked. */
1720	if (slot->state < AHCI_SLOT_EXECUTING) {
1721		/* Check if slot started executing. */
1722		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1723		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1724		    >> AHCI_P_CMD_CCS_SHIFT;
1725		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot ||
1726		    ch->fbs_enabled)
1727			slot->state = AHCI_SLOT_EXECUTING;
1728
1729		callout_reset(&slot->timeout,
1730		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1731		    (timeout_t*)ahci_timeout, slot);
1732		return;
1733	}
1734
1735	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1736	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1737	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1738	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1739	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1740
1741	/* Handle frozen command. */
1742	if (ch->frozen) {
1743		union ccb *fccb = ch->frozen;
1744		ch->frozen = NULL;
1745		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1746		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1747			xpt_freeze_devq(fccb->ccb_h.path, 1);
1748			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1749		}
1750		xpt_done(fccb);
1751	}
1752	if (!ch->fbs_enabled) {
1753		/* Without FBS we know real timeout source. */
1754		ch->fatalerr = 1;
1755		/* Handle command with timeout. */
1756		ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1757		/* Handle the rest of commands. */
1758		for (i = 0; i < ch->numslots; i++) {
1759			/* Do we have a running request on slot? */
1760			if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1761				continue;
1762			ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1763		}
1764	} else {
1765		/* With FBS we wait for other commands timeout and pray. */
1766		if (ch->toslots == 0)
1767			xpt_freeze_simq(ch->sim, 1);
1768		ch->toslots |= (1 << slot->slot);
1769		if ((ch->rslots & ~ch->toslots) == 0)
1770			ahci_process_timeout(dev);
1771		else
1772			device_printf(dev, " ... waiting for slots %08x\n",
1773			    ch->rslots & ~ch->toslots);
1774	}
1775}
1776
1777/* Must be called with channel locked. */
1778static void
1779ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1780{
1781	device_t dev = slot->dev;
1782	struct ahci_channel *ch = device_get_softc(dev);
1783	union ccb *ccb = slot->ccb;
1784
1785	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1786	    BUS_DMASYNC_POSTWRITE);
1787	/* Read result registers to the result struct
1788	 * May be incorrect if several commands finished same time,
1789	 * so read only when sure or have to.
1790	 */
1791	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1792		struct ata_res *res = &ccb->ataio.res;
1793
1794		if ((et == AHCI_ERR_TFE) ||
1795		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1796			u_int8_t *fis = ch->dma.rfis + 0x40;
1797
1798			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1799			    BUS_DMASYNC_POSTREAD);
1800			if (ch->fbs_enabled) {
1801				fis += ccb->ccb_h.target_id * 256;
1802				res->status = fis[2];
1803				res->error = fis[3];
1804			} else {
1805				uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1806
1807				res->status = tfd;
1808				res->error = tfd >> 8;
1809			}
1810			res->lba_low = fis[4];
1811			res->lba_mid = fis[5];
1812			res->lba_high = fis[6];
1813			res->device = fis[7];
1814			res->lba_low_exp = fis[8];
1815			res->lba_mid_exp = fis[9];
1816			res->lba_high_exp = fis[10];
1817			res->sector_count = fis[12];
1818			res->sector_count_exp = fis[13];
1819		} else
1820			bzero(res, sizeof(*res));
1821	}
1822	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1823		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1824		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1825		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1826		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1827	}
1828	if (et != AHCI_ERR_NONE)
1829		ch->eslots |= (1 << slot->slot);
1830	/* In case of error, freeze device for proper recovery. */
1831	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1832	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1833		xpt_freeze_devq(ccb->ccb_h.path, 1);
1834		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1835	}
1836	/* Set proper result status. */
1837	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1838	switch (et) {
1839	case AHCI_ERR_NONE:
1840		ccb->ccb_h.status |= CAM_REQ_CMP;
1841		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1842			ccb->csio.scsi_status = SCSI_STATUS_OK;
1843		break;
1844	case AHCI_ERR_INVALID:
1845		ch->fatalerr = 1;
1846		ccb->ccb_h.status |= CAM_REQ_INVALID;
1847		break;
1848	case AHCI_ERR_INNOCENT:
1849		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1850		break;
1851	case AHCI_ERR_TFE:
1852	case AHCI_ERR_NCQ:
1853		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1854			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1855			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1856		} else {
1857			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1858		}
1859		break;
1860	case AHCI_ERR_SATA:
1861		ch->fatalerr = 1;
1862		if (!ch->readlog) {
1863			xpt_freeze_simq(ch->sim, 1);
1864			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1865			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1866		}
1867		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1868		break;
1869	case AHCI_ERR_TIMEOUT:
1870		if (!ch->readlog) {
1871			xpt_freeze_simq(ch->sim, 1);
1872			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1873			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1874		}
1875		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1876		break;
1877	default:
1878		ch->fatalerr = 1;
1879		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1880	}
1881	/* Free slot. */
1882	ch->oslots &= ~(1 << slot->slot);
1883	ch->rslots &= ~(1 << slot->slot);
1884	ch->aslots &= ~(1 << slot->slot);
1885	if (et != AHCI_ERR_TIMEOUT) {
1886		if (ch->toslots == (1 << slot->slot))
1887			xpt_release_simq(ch->sim, TRUE);
1888		ch->toslots &= ~(1 << slot->slot);
1889	}
1890	slot->state = AHCI_SLOT_EMPTY;
1891	slot->ccb = NULL;
1892	/* Update channel stats. */
1893	ch->numrslots--;
1894	ch->numrslotspd[ccb->ccb_h.target_id]--;
1895	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1896	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1897		ch->numtslots--;
1898		ch->numtslotspd[ccb->ccb_h.target_id]--;
1899	}
1900	/* If it was first request of reset sequence and there is no error,
1901	 * proceed to second request. */
1902	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1903	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1904	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1905	    et == AHCI_ERR_NONE) {
1906		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1907		ahci_begin_transaction(dev, ccb);
1908		return;
1909	}
1910	/* If it was our READ LOG command - process it. */
1911	if (ch->readlog) {
1912		ahci_process_read_log(dev, ccb);
1913	/* If it was NCQ command error, put result on hold. */
1914	} else if (et == AHCI_ERR_NCQ) {
1915		ch->hold[slot->slot] = ccb;
1916		ch->numhslots++;
1917	} else
1918		xpt_done(ccb);
1919	/* Unfreeze frozen command. */
1920	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
1921		union ccb *fccb = ch->frozen;
1922		ch->frozen = NULL;
1923		ahci_begin_transaction(dev, fccb);
1924		xpt_release_simq(ch->sim, TRUE);
1925	}
1926	/* If we have no other active commands, ... */
1927	if (ch->rslots == 0) {
1928		/* if there was fatal error - reset port. */
1929		if (ch->toslots != 0 || ch->fatalerr) {
1930			ahci_reset(dev);
1931		} else {
1932			/* if we have slots in error, we can reinit port. */
1933			if (ch->eslots != 0) {
1934				ahci_stop(dev);
1935				ahci_start(dev, 1);
1936			}
1937			/* if there commands on hold, we can do READ LOG. */
1938			if (!ch->readlog && ch->numhslots)
1939				ahci_issue_read_log(dev);
1940		}
1941	/* If all the rest of commands are in timeout - give them chance. */
1942	} else if ((ch->rslots & ~ch->toslots) == 0 &&
1943	    et != AHCI_ERR_TIMEOUT)
1944		ahci_rearm_timeout(dev);
1945	/* Start PM timer. */
1946	if (ch->numrslots == 0 && ch->pm_level > 3) {
1947		callout_schedule(&ch->pm_timer,
1948		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1949	}
1950}
1951
1952static void
1953ahci_issue_read_log(device_t dev)
1954{
1955	struct ahci_channel *ch = device_get_softc(dev);
1956	union ccb *ccb;
1957	struct ccb_ataio *ataio;
1958	int i;
1959
1960	ch->readlog = 1;
1961	/* Find some holden command. */
1962	for (i = 0; i < ch->numslots; i++) {
1963		if (ch->hold[i])
1964			break;
1965	}
1966	ccb = xpt_alloc_ccb_nowait();
1967	if (ccb == NULL) {
1968		device_printf(dev, "Unable allocate READ LOG command");
1969		return; /* XXX */
1970	}
1971	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1972	ccb->ccb_h.func_code = XPT_ATA_IO;
1973	ccb->ccb_h.flags = CAM_DIR_IN;
1974	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1975	ataio = &ccb->ataio;
1976	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1977	if (ataio->data_ptr == NULL) {
1978		device_printf(dev, "Unable allocate memory for READ LOG command");
1979		return; /* XXX */
1980	}
1981	ataio->dxfer_len = 512;
1982	bzero(&ataio->cmd, sizeof(ataio->cmd));
1983	ataio->cmd.flags = CAM_ATAIO_48BIT;
1984	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1985	ataio->cmd.sector_count = 1;
1986	ataio->cmd.sector_count_exp = 0;
1987	ataio->cmd.lba_low = 0x10;
1988	ataio->cmd.lba_mid = 0;
1989	ataio->cmd.lba_mid_exp = 0;
1990	/* Freeze SIM while doing READ LOG EXT. */
1991	xpt_freeze_simq(ch->sim, 1);
1992	ahci_begin_transaction(dev, ccb);
1993}
1994
1995static void
1996ahci_process_read_log(device_t dev, union ccb *ccb)
1997{
1998	struct ahci_channel *ch = device_get_softc(dev);
1999	uint8_t *data;
2000	struct ata_res *res;
2001	int i;
2002
2003	ch->readlog = 0;
2004
2005	data = ccb->ataio.data_ptr;
2006	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
2007	    (data[0] & 0x80) == 0) {
2008		for (i = 0; i < ch->numslots; i++) {
2009			if (!ch->hold[i])
2010				continue;
2011			if ((data[0] & 0x1F) == i) {
2012				res = &ch->hold[i]->ataio.res;
2013				res->status = data[2];
2014				res->error = data[3];
2015				res->lba_low = data[4];
2016				res->lba_mid = data[5];
2017				res->lba_high = data[6];
2018				res->device = data[7];
2019				res->lba_low_exp = data[8];
2020				res->lba_mid_exp = data[9];
2021				res->lba_high_exp = data[10];
2022				res->sector_count = data[12];
2023				res->sector_count_exp = data[13];
2024			} else {
2025				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
2026				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
2027			}
2028			xpt_done(ch->hold[i]);
2029			ch->hold[i] = NULL;
2030			ch->numhslots--;
2031		}
2032	} else {
2033		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
2034			device_printf(dev, "Error while READ LOG EXT\n");
2035		else if ((data[0] & 0x80) == 0) {
2036			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
2037		}
2038		for (i = 0; i < ch->numslots; i++) {
2039			if (!ch->hold[i])
2040				continue;
2041			xpt_done(ch->hold[i]);
2042			ch->hold[i] = NULL;
2043			ch->numhslots--;
2044		}
2045	}
2046	free(ccb->ataio.data_ptr, M_AHCI);
2047	xpt_free_ccb(ccb);
2048	xpt_release_simq(ch->sim, TRUE);
2049}
2050
2051static void
2052ahci_start(device_t dev, int fbs)
2053{
2054	struct ahci_channel *ch = device_get_softc(dev);
2055	u_int32_t cmd;
2056
2057	/* Clear SATA error register */
2058	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
2059	/* Clear any interrupts pending on this channel */
2060	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
2061	/* Configure FIS-based switching if supported. */
2062	if (ch->chcaps & AHCI_P_CMD_FBSCP) {
2063		ch->fbs_enabled = (fbs && ch->pm_present) ? 1 : 0;
2064		ATA_OUTL(ch->r_mem, AHCI_P_FBS,
2065		    ch->fbs_enabled ? AHCI_P_FBS_EN : 0);
2066	}
2067	/* Start operations on this channel */
2068	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2069	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
2070	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
2071}
2072
2073static void
2074ahci_stop(device_t dev)
2075{
2076	struct ahci_channel *ch = device_get_softc(dev);
2077	u_int32_t cmd;
2078	int timeout;
2079
2080	/* Kill all activity on this channel */
2081	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2082	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
2083	/* Wait for activity stop. */
2084	timeout = 0;
2085	do {
2086		DELAY(1000);
2087		if (timeout++ > 1000) {
2088			device_printf(dev, "stopping AHCI engine failed\n");
2089			break;
2090		}
2091	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
2092	ch->eslots = 0;
2093}
2094
2095static void
2096ahci_clo(device_t dev)
2097{
2098	struct ahci_channel *ch = device_get_softc(dev);
2099	u_int32_t cmd;
2100	int timeout;
2101
2102	/* Issue Command List Override if supported */
2103	if (ch->caps & AHCI_CAP_SCLO) {
2104		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2105		cmd |= AHCI_P_CMD_CLO;
2106		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
2107		timeout = 0;
2108		do {
2109			DELAY(1000);
2110			if (timeout++ > 1000) {
2111			    device_printf(dev, "executing CLO failed\n");
2112			    break;
2113			}
2114		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
2115	}
2116}
2117
2118static void
2119ahci_stop_fr(device_t dev)
2120{
2121	struct ahci_channel *ch = device_get_softc(dev);
2122	u_int32_t cmd;
2123	int timeout;
2124
2125	/* Kill all FIS reception on this channel */
2126	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2127	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
2128	/* Wait for FIS reception stop. */
2129	timeout = 0;
2130	do {
2131		DELAY(1000);
2132		if (timeout++ > 1000) {
2133			device_printf(dev, "stopping AHCI FR engine failed\n");
2134			break;
2135		}
2136	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
2137}
2138
2139static void
2140ahci_start_fr(device_t dev)
2141{
2142	struct ahci_channel *ch = device_get_softc(dev);
2143	u_int32_t cmd;
2144
2145	/* Start FIS reception on this channel */
2146	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
2147	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
2148}
2149
2150static int
2151ahci_wait_ready(device_t dev, int t)
2152{
2153	struct ahci_channel *ch = device_get_softc(dev);
2154	int timeout = 0;
2155	uint32_t val;
2156
2157	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
2158	    (ATA_S_BUSY | ATA_S_DRQ)) {
2159		DELAY(1000);
2160		if (timeout++ > t) {
2161			device_printf(dev, "device is not ready (timeout %dms) "
2162			    "tfd = %08x\n", t, val);
2163			return (EBUSY);
2164		}
2165	}
2166	if (bootverbose)
2167		device_printf(dev, "ready wait time=%dms\n", timeout);
2168	return (0);
2169}
2170
2171static void
2172ahci_reset(device_t dev)
2173{
2174	struct ahci_channel *ch = device_get_softc(dev);
2175	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
2176	int i;
2177
2178	xpt_freeze_simq(ch->sim, 1);
2179	if (bootverbose)
2180		device_printf(dev, "AHCI reset...\n");
2181	/* Requeue freezed command. */
2182	if (ch->frozen) {
2183		union ccb *fccb = ch->frozen;
2184		ch->frozen = NULL;
2185		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
2186		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
2187			xpt_freeze_devq(fccb->ccb_h.path, 1);
2188			fccb->ccb_h.status |= CAM_DEV_QFRZN;
2189		}
2190		xpt_done(fccb);
2191	}
2192	/* Kill the engine and requeue all running commands. */
2193	ahci_stop(dev);
2194	for (i = 0; i < ch->numslots; i++) {
2195		/* Do we have a running request on slot? */
2196		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
2197			continue;
2198		/* XXX; Commands in loading state. */
2199		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
2200	}
2201	for (i = 0; i < ch->numslots; i++) {
2202		if (!ch->hold[i])
2203			continue;
2204		xpt_done(ch->hold[i]);
2205		ch->hold[i] = NULL;
2206		ch->numhslots--;
2207	}
2208	if (ch->toslots != 0)
2209		xpt_release_simq(ch->sim, TRUE);
2210	ch->eslots = 0;
2211	ch->toslots = 0;
2212	ch->fatalerr = 0;
2213	/* Tell the XPT about the event */
2214	xpt_async(AC_BUS_RESET, ch->path, NULL);
2215	/* Disable port interrupts */
2216	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
2217	/* Reset and reconnect PHY, */
2218	if (!ahci_sata_phy_reset(dev)) {
2219		if (bootverbose)
2220			device_printf(dev,
2221			    "AHCI reset done: phy reset found no device\n");
2222		ch->devices = 0;
2223		/* Enable wanted port interrupts */
2224		ATA_OUTL(ch->r_mem, AHCI_P_IE,
2225		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
2226		xpt_release_simq(ch->sim, TRUE);
2227		return;
2228	}
2229	/* Wait for clearing busy status. */
2230	if (ahci_wait_ready(dev, 15000))
2231		ahci_clo(dev);
2232	ahci_start(dev, 1);
2233	ch->devices = 1;
2234	/* Enable wanted port interrupts */
2235	ATA_OUTL(ch->r_mem, AHCI_P_IE,
2236	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
2237	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
2238	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
2239	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
2240	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
2241	if (bootverbose)
2242		device_printf(dev, "AHCI reset done: device found\n");
2243	xpt_release_simq(ch->sim, TRUE);
2244}
2245
2246static int
2247ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
2248{
2249	struct ahci_channel *ch = device_get_softc(dev);
2250	u_int8_t *fis = &ctp->cfis[0];
2251
2252	bzero(ctp->cfis, 64);
2253	fis[0] = 0x27;  		/* host to device */
2254	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2255	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2256		fis[1] |= 0x80;
2257		fis[2] = ATA_PACKET_CMD;
2258		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2259		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2260			fis[3] = ATA_F_DMA;
2261		else {
2262			fis[5] = ccb->csio.dxfer_len;
2263		        fis[6] = ccb->csio.dxfer_len >> 8;
2264		}
2265		fis[7] = ATA_D_LBA;
2266		fis[15] = ATA_A_4BIT;
2267		bzero(ctp->acmd, 32);
2268		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2269		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2270		    ctp->acmd, ccb->csio.cdb_len);
2271	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2272		fis[1] |= 0x80;
2273		fis[2] = ccb->ataio.cmd.command;
2274		fis[3] = ccb->ataio.cmd.features;
2275		fis[4] = ccb->ataio.cmd.lba_low;
2276		fis[5] = ccb->ataio.cmd.lba_mid;
2277		fis[6] = ccb->ataio.cmd.lba_high;
2278		fis[7] = ccb->ataio.cmd.device;
2279		fis[8] = ccb->ataio.cmd.lba_low_exp;
2280		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2281		fis[10] = ccb->ataio.cmd.lba_high_exp;
2282		fis[11] = ccb->ataio.cmd.features_exp;
2283		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2284			fis[12] = tag << 3;
2285			fis[13] = 0;
2286		} else {
2287			fis[12] = ccb->ataio.cmd.sector_count;
2288			fis[13] = ccb->ataio.cmd.sector_count_exp;
2289		}
2290		fis[15] = ATA_A_4BIT;
2291	} else {
2292		fis[15] = ccb->ataio.cmd.control;
2293	}
2294	return (20);
2295}
2296
2297static int
2298ahci_sata_connect(struct ahci_channel *ch)
2299{
2300	u_int32_t status;
2301	int timeout;
2302
2303	/* Wait up to 100ms for "connect well" */
2304	for (timeout = 0; timeout < 100 ; timeout++) {
2305		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2306		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2307		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2308		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2309			break;
2310		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2311			if (bootverbose) {
2312				device_printf(ch->dev, "SATA offline status=%08x\n",
2313				    status);
2314			}
2315			return (0);
2316		}
2317		DELAY(1000);
2318	}
2319	if (timeout >= 100) {
2320		if (bootverbose) {
2321			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2322			    status);
2323		}
2324		return (0);
2325	}
2326	if (bootverbose) {
2327		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2328		    timeout, status);
2329	}
2330	/* Clear SATA error register */
2331	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2332	return (1);
2333}
2334
2335static int
2336ahci_sata_phy_reset(device_t dev)
2337{
2338	struct ahci_channel *ch = device_get_softc(dev);
2339	int sata_rev;
2340	uint32_t val;
2341
2342	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2343	if (sata_rev == 1)
2344		val = ATA_SC_SPD_SPEED_GEN1;
2345	else if (sata_rev == 2)
2346		val = ATA_SC_SPD_SPEED_GEN2;
2347	else if (sata_rev == 3)
2348		val = ATA_SC_SPD_SPEED_GEN3;
2349	else
2350		val = 0;
2351	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2352	    ATA_SC_DET_RESET | val |
2353	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2354	DELAY(5000);
2355	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2356	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2357	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2358	DELAY(5000);
2359	if (!ahci_sata_connect(ch)) {
2360		if (ch->pm_level > 0)
2361			ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
2362		return (0);
2363	}
2364	return (1);
2365}
2366
2367static void
2368ahciaction(struct cam_sim *sim, union ccb *ccb)
2369{
2370	device_t dev;
2371	struct ahci_channel *ch;
2372
2373	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2374	    ccb->ccb_h.func_code));
2375
2376	ch = (struct ahci_channel *)cam_sim_softc(sim);
2377	dev = ch->dev;
2378	switch (ccb->ccb_h.func_code) {
2379	/* Common cases first */
2380	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2381	case XPT_SCSI_IO:
2382		if (ch->devices == 0) {
2383			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2384			xpt_done(ccb);
2385			break;
2386		}
2387		/* Check for command collision. */
2388		if (ahci_check_collision(dev, ccb)) {
2389			/* Freeze command. */
2390			ch->frozen = ccb;
2391			/* We have only one frozen slot, so freeze simq also. */
2392			xpt_freeze_simq(ch->sim, 1);
2393			return;
2394		}
2395		ahci_begin_transaction(dev, ccb);
2396		break;
2397	case XPT_EN_LUN:		/* Enable LUN as a target */
2398	case XPT_TARGET_IO:		/* Execute target I/O request */
2399	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2400	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2401	case XPT_ABORT:			/* Abort the specified CCB */
2402		/* XXX Implement */
2403		ccb->ccb_h.status = CAM_REQ_INVALID;
2404		xpt_done(ccb);
2405		break;
2406	case XPT_SET_TRAN_SETTINGS:
2407	{
2408		struct	ccb_trans_settings *cts = &ccb->cts;
2409		struct	ahci_device *d;
2410
2411		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2412			d = &ch->curr[ccb->ccb_h.target_id];
2413		else
2414			d = &ch->user[ccb->ccb_h.target_id];
2415		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2416			d->revision = cts->xport_specific.sata.revision;
2417		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2418			d->mode = cts->xport_specific.sata.mode;
2419		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2420			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2421		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2422			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2423		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2424			ch->pm_present = cts->xport_specific.sata.pm_present;
2425		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_ATAPI)
2426			d->atapi = cts->xport_specific.sata.atapi;
2427		ccb->ccb_h.status = CAM_REQ_CMP;
2428		xpt_done(ccb);
2429		break;
2430	}
2431	case XPT_GET_TRAN_SETTINGS:
2432	/* Get default/user set transfer settings for the target */
2433	{
2434		struct	ccb_trans_settings *cts = &ccb->cts;
2435		struct  ahci_device *d;
2436		uint32_t status;
2437
2438		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2439			d = &ch->curr[ccb->ccb_h.target_id];
2440		else
2441			d = &ch->user[ccb->ccb_h.target_id];
2442		cts->protocol = PROTO_ATA;
2443		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2444		cts->transport = XPORT_SATA;
2445		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2446		cts->proto_specific.valid = 0;
2447		cts->xport_specific.sata.valid = 0;
2448		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2449		    (ccb->ccb_h.target_id == 15 ||
2450		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2451			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2452			if (status & 0x0f0) {
2453				cts->xport_specific.sata.revision =
2454				    (status & 0x0f0) >> 4;
2455				cts->xport_specific.sata.valid |=
2456				    CTS_SATA_VALID_REVISION;
2457			}
2458		} else {
2459			cts->xport_specific.sata.revision = d->revision;
2460			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2461		}
2462		cts->xport_specific.sata.mode = d->mode;
2463		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2464		cts->xport_specific.sata.bytecount = d->bytecount;
2465		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2466		cts->xport_specific.sata.pm_present = ch->pm_present;
2467		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2468		cts->xport_specific.sata.tags = d->tags;
2469		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2470		cts->xport_specific.sata.atapi = d->atapi;
2471		cts->xport_specific.sata.valid |= CTS_SATA_VALID_ATAPI;
2472		ccb->ccb_h.status = CAM_REQ_CMP;
2473		xpt_done(ccb);
2474		break;
2475	}
2476#if 0
2477	case XPT_CALC_GEOMETRY:
2478	{
2479		struct	  ccb_calc_geometry *ccg;
2480		uint32_t size_mb;
2481		uint32_t secs_per_cylinder;
2482
2483		ccg = &ccb->ccg;
2484		size_mb = ccg->volume_size
2485			/ ((1024L * 1024L) / ccg->block_size);
2486		if (size_mb >= 1024 && (aha->extended_trans != 0)) {
2487			if (size_mb >= 2048) {
2488				ccg->heads = 255;
2489				ccg->secs_per_track = 63;
2490			} else {
2491				ccg->heads = 128;
2492				ccg->secs_per_track = 32;
2493			}
2494		} else {
2495			ccg->heads = 64;
2496			ccg->secs_per_track = 32;
2497		}
2498		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2499		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2500		ccb->ccb_h.status = CAM_REQ_CMP;
2501		xpt_done(ccb);
2502		break;
2503	}
2504#endif
2505	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2506	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2507		ahci_reset(dev);
2508		ccb->ccb_h.status = CAM_REQ_CMP;
2509		xpt_done(ccb);
2510		break;
2511	case XPT_TERM_IO:		/* Terminate the I/O process */
2512		/* XXX Implement */
2513		ccb->ccb_h.status = CAM_REQ_INVALID;
2514		xpt_done(ccb);
2515		break;
2516	case XPT_PATH_INQ:		/* Path routing inquiry */
2517	{
2518		struct ccb_pathinq *cpi = &ccb->cpi;
2519
2520		cpi->version_num = 1; /* XXX??? */
2521		cpi->hba_inquiry = PI_SDTR_ABLE;
2522		if (ch->caps & AHCI_CAP_SNCQ)
2523			cpi->hba_inquiry |= PI_TAG_ABLE;
2524		if (ch->caps & AHCI_CAP_SPM)
2525			cpi->hba_inquiry |= PI_SATAPM;
2526		cpi->target_sprt = 0;
2527		cpi->hba_misc = PIM_SEQSCAN;
2528		cpi->hba_eng_cnt = 0;
2529		if (ch->caps & AHCI_CAP_SPM)
2530			cpi->max_target = 15;
2531		else
2532			cpi->max_target = 0;
2533		cpi->max_lun = 0;
2534		cpi->initiator_id = 0;
2535		cpi->bus_id = cam_sim_bus(sim);
2536		cpi->base_transfer_speed = 150000;
2537		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2538		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2539		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2540		cpi->unit_number = cam_sim_unit(sim);
2541		cpi->transport = XPORT_SATA;
2542		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2543		cpi->protocol = PROTO_ATA;
2544		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2545		cpi->maxio = MAXPHYS;
2546		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2547		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
2548			cpi->maxio = min(cpi->maxio, 128 * 512);
2549		cpi->ccb_h.status = CAM_REQ_CMP;
2550		xpt_done(ccb);
2551		break;
2552	}
2553	default:
2554		ccb->ccb_h.status = CAM_REQ_INVALID;
2555		xpt_done(ccb);
2556		break;
2557	}
2558}
2559
2560static void
2561ahcipoll(struct cam_sim *sim)
2562{
2563	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2564
2565	ahci_ch_intr(ch->dev);
2566}
2567