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