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