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