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