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