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