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