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