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