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