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