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