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