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