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