xref: /freebsd/sys/dev/ahci/ahci.c (revision eb6d21b4ca6d668cf89afd99eef7baeafa712197)
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",	0},
119 	{0x26538086, "Intel ICH6M",	0},
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 	for (; unit < ctlr->channels; unit++) {
600 		if ((is & (1 << unit)) != 0 &&
601 		    (arg = ctlr->interrupt[unit].argument)) {
602 			if (ctlr->quirks & AHCI_Q_EDGEIS) {
603 				/* Some controller have edge triggered IS. */
604 				ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
605 				ctlr->interrupt[unit].function(arg);
606 			} else {
607 				/* but AHCI declares level triggered IS. */
608 				ctlr->interrupt[unit].function(arg);
609 				ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
610 			}
611 		}
612 	}
613 }
614 
615 /*
616  * Simplified interrupt handler for multivector MSI mode.
617  */
618 static void
619 ahci_intr_one(void *data)
620 {
621 	struct ahci_controller_irq *irq = data;
622 	struct ahci_controller *ctlr = irq->ctlr;
623 	void *arg;
624 	int unit;
625 
626 	unit = irq->r_irq_rid - 1;
627 	if ((arg = ctlr->interrupt[unit].argument))
628 	    ctlr->interrupt[unit].function(arg);
629 }
630 
631 static struct resource *
632 ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
633 		       u_long start, u_long end, u_long count, u_int flags)
634 {
635 	struct ahci_controller *ctlr = device_get_softc(dev);
636 	int unit = ((struct ahci_channel *)device_get_softc(child))->unit;
637 	struct resource *res = NULL;
638 	int offset = AHCI_OFFSET + (unit << 7);
639 	long st;
640 
641 	switch (type) {
642 	case SYS_RES_MEMORY:
643 		st = rman_get_start(ctlr->r_mem);
644 		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
645 		    st + offset + 127, 128, RF_ACTIVE, child);
646 		if (res) {
647 			bus_space_handle_t bsh;
648 			bus_space_tag_t bst;
649 			bsh = rman_get_bushandle(ctlr->r_mem);
650 			bst = rman_get_bustag(ctlr->r_mem);
651 			bus_space_subregion(bst, bsh, offset, 128, &bsh);
652 			rman_set_bushandle(res, bsh);
653 			rman_set_bustag(res, bst);
654 		}
655 		break;
656 	case SYS_RES_IRQ:
657 		if (*rid == ATA_IRQ_RID)
658 			res = ctlr->irqs[0].r_irq;
659 		break;
660 	}
661 	return (res);
662 }
663 
664 static int
665 ahci_release_resource(device_t dev, device_t child, int type, int rid,
666 			 struct resource *r)
667 {
668 
669 	switch (type) {
670 	case SYS_RES_MEMORY:
671 		rman_release_resource(r);
672 		return (0);
673 	case SYS_RES_IRQ:
674 		if (rid != ATA_IRQ_RID)
675 			return ENOENT;
676 		return (0);
677 	}
678 	return (EINVAL);
679 }
680 
681 static int
682 ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
683 		   int flags, driver_filter_t *filter, driver_intr_t *function,
684 		   void *argument, void **cookiep)
685 {
686 	struct ahci_controller *ctlr = device_get_softc(dev);
687 	int unit = (intptr_t)device_get_ivars(child);
688 
689 	if (filter != NULL) {
690 		printf("ahci.c: we cannot use a filter here\n");
691 		return (EINVAL);
692 	}
693 	ctlr->interrupt[unit].function = function;
694 	ctlr->interrupt[unit].argument = argument;
695 	return (0);
696 }
697 
698 static int
699 ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
700 		      void *cookie)
701 {
702 	struct ahci_controller *ctlr = device_get_softc(dev);
703 	int unit = (intptr_t)device_get_ivars(child);
704 
705 	ctlr->interrupt[unit].function = NULL;
706 	ctlr->interrupt[unit].argument = NULL;
707 	return (0);
708 }
709 
710 static int
711 ahci_print_child(device_t dev, device_t child)
712 {
713 	int retval;
714 
715 	retval = bus_print_child_header(dev, child);
716 	retval += printf(" at channel %d",
717 	    (int)(intptr_t)device_get_ivars(child));
718 	retval += bus_print_child_footer(dev, child);
719 
720 	return (retval);
721 }
722 
723 devclass_t ahci_devclass;
724 static device_method_t ahci_methods[] = {
725 	DEVMETHOD(device_probe,     ahci_probe),
726 	DEVMETHOD(device_attach,    ahci_attach),
727 	DEVMETHOD(device_detach,    ahci_detach),
728 	DEVMETHOD(device_suspend,   ahci_suspend),
729 	DEVMETHOD(device_resume,    ahci_resume),
730 	DEVMETHOD(bus_print_child,  ahci_print_child),
731 	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
732 	DEVMETHOD(bus_release_resource,     ahci_release_resource),
733 	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
734 	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
735 	{ 0, 0 }
736 };
737 static driver_t ahci_driver = {
738         "ahci",
739         ahci_methods,
740         sizeof(struct ahci_controller)
741 };
742 DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
743 static device_method_t ahci_ata_methods[] = {
744 	DEVMETHOD(device_probe,     ahci_ata_probe),
745 	DEVMETHOD(device_attach,    ahci_attach),
746 	DEVMETHOD(device_detach,    ahci_detach),
747 	DEVMETHOD(device_suspend,   ahci_suspend),
748 	DEVMETHOD(device_resume,    ahci_resume),
749 	DEVMETHOD(bus_print_child,  ahci_print_child),
750 	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
751 	DEVMETHOD(bus_release_resource,     ahci_release_resource),
752 	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
753 	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
754 	{ 0, 0 }
755 };
756 static driver_t ahci_ata_driver = {
757         "ahci",
758         ahci_ata_methods,
759         sizeof(struct ahci_controller)
760 };
761 DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
762 MODULE_VERSION(ahci, 1);
763 MODULE_DEPEND(ahci, cam, 1, 1, 1);
764 
765 static int
766 ahci_ch_probe(device_t dev)
767 {
768 
769 	device_set_desc_copy(dev, "AHCI channel");
770 	return (0);
771 }
772 
773 static int
774 ahci_ch_attach(device_t dev)
775 {
776 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
777 	struct ahci_channel *ch = device_get_softc(dev);
778 	struct cam_devq *devq;
779 	int rid, error, i, sata_rev = 0;
780 
781 	ch->dev = dev;
782 	ch->unit = (intptr_t)device_get_ivars(dev);
783 	ch->caps = ctlr->caps;
784 	ch->caps2 = ctlr->caps2;
785 	ch->quirks = ctlr->quirks;
786 	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
787 	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
788 	resource_int_value(device_get_name(dev),
789 	    device_get_unit(dev), "pm_level", &ch->pm_level);
790 	if (ch->pm_level > 3)
791 		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
792 	/* Limit speed for my onboard JMicron external port.
793 	 * It is not eSATA really. */
794 	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
795 	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
796 	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
797 	    ch->unit == 0)
798 		sata_rev = 1;
799 	resource_int_value(device_get_name(dev),
800 	    device_get_unit(dev), "sata_rev", &sata_rev);
801 	for (i = 0; i < 16; i++) {
802 		ch->user[i].revision = sata_rev;
803 		ch->user[i].mode = 0;
804 		ch->user[i].bytecount = 8192;
805 		ch->user[i].tags = ch->numslots;
806 		ch->curr[i] = ch->user[i];
807 	}
808 	rid = ch->unit;
809 	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
810 	    &rid, RF_ACTIVE)))
811 		return (ENXIO);
812 	ahci_dmainit(dev);
813 	ahci_slotsalloc(dev);
814 	ahci_ch_resume(dev);
815 	mtx_lock(&ch->mtx);
816 	rid = ATA_IRQ_RID;
817 	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
818 	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
819 		bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
820 		device_printf(dev, "Unable to map interrupt\n");
821 		return (ENXIO);
822 	}
823 	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
824 	    ahci_ch_intr_locked, dev, &ch->ih))) {
825 		device_printf(dev, "Unable to setup interrupt\n");
826 		error = ENXIO;
827 		goto err1;
828 	}
829 	/* Create the device queue for our SIM. */
830 	devq = cam_simq_alloc(ch->numslots);
831 	if (devq == NULL) {
832 		device_printf(dev, "Unable to allocate simq\n");
833 		error = ENOMEM;
834 		goto err1;
835 	}
836 	/* Construct SIM entry */
837 	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
838 	    device_get_unit(dev), &ch->mtx,
839 	    min(2, ch->numslots),
840 	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
841 	    devq);
842 	if (ch->sim == NULL) {
843 		device_printf(dev, "unable to allocate sim\n");
844 		error = ENOMEM;
845 		goto err2;
846 	}
847 	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
848 		device_printf(dev, "unable to register xpt bus\n");
849 		error = ENXIO;
850 		goto err2;
851 	}
852 	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
853 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
854 		device_printf(dev, "unable to create path\n");
855 		error = ENXIO;
856 		goto err3;
857 	}
858 	if (ch->pm_level > 3) {
859 		callout_reset(&ch->pm_timer,
860 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
861 		    ahci_ch_pm, dev);
862 	}
863 	mtx_unlock(&ch->mtx);
864 	return (0);
865 
866 err3:
867 	xpt_bus_deregister(cam_sim_path(ch->sim));
868 err2:
869 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
870 err1:
871 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
872 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
873 	mtx_unlock(&ch->mtx);
874 	return (error);
875 }
876 
877 static int
878 ahci_ch_detach(device_t dev)
879 {
880 	struct ahci_channel *ch = device_get_softc(dev);
881 
882 	mtx_lock(&ch->mtx);
883 	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
884 	xpt_free_path(ch->path);
885 	xpt_bus_deregister(cam_sim_path(ch->sim));
886 	cam_sim_free(ch->sim, /*free_devq*/TRUE);
887 	mtx_unlock(&ch->mtx);
888 
889 	if (ch->pm_level > 3)
890 		callout_drain(&ch->pm_timer);
891 	bus_teardown_intr(dev, ch->r_irq, ch->ih);
892 	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
893 
894 	ahci_ch_suspend(dev);
895 	ahci_slotsfree(dev);
896 	ahci_dmafini(dev);
897 
898 	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
899 	mtx_destroy(&ch->mtx);
900 	return (0);
901 }
902 
903 static int
904 ahci_ch_suspend(device_t dev)
905 {
906 	struct ahci_channel *ch = device_get_softc(dev);
907 
908 	/* Disable port interrupts. */
909 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
910 	/* Reset command register. */
911 	ahci_stop(dev);
912 	ahci_stop_fr(dev);
913 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
914 	/* Allow everything, including partial and slumber modes. */
915 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
916 	/* Request slumber mode transition and give some time to get there. */
917 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
918 	DELAY(100);
919 	/* Disable PHY. */
920 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
921 	return (0);
922 }
923 
924 static int
925 ahci_ch_resume(device_t dev)
926 {
927 	struct ahci_channel *ch = device_get_softc(dev);
928 	uint64_t work;
929 
930 	/* Disable port interrupts */
931 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
932 	/* Setup work areas */
933 	work = ch->dma.work_bus + AHCI_CL_OFFSET;
934 	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
935 	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
936 	work = ch->dma.rfis_bus;
937 	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
938 	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
939 	/* Activate the channel and power/spin up device */
940 	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
941 	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
942 	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
943 	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
944 	ahci_start_fr(dev);
945 	ahci_start(dev);
946 	return (0);
947 }
948 
949 devclass_t ahcich_devclass;
950 static device_method_t ahcich_methods[] = {
951 	DEVMETHOD(device_probe,     ahci_ch_probe),
952 	DEVMETHOD(device_attach,    ahci_ch_attach),
953 	DEVMETHOD(device_detach,    ahci_ch_detach),
954 	DEVMETHOD(device_suspend,   ahci_ch_suspend),
955 	DEVMETHOD(device_resume,    ahci_ch_resume),
956 	{ 0, 0 }
957 };
958 static driver_t ahcich_driver = {
959         "ahcich",
960         ahcich_methods,
961         sizeof(struct ahci_channel)
962 };
963 DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
964 
965 struct ahci_dc_cb_args {
966 	bus_addr_t maddr;
967 	int error;
968 };
969 
970 static void
971 ahci_dmainit(device_t dev)
972 {
973 	struct ahci_channel *ch = device_get_softc(dev);
974 	struct ahci_dc_cb_args dcba;
975 
976 	if (ch->caps & AHCI_CAP_64BIT)
977 		ch->dma.max_address = BUS_SPACE_MAXADDR;
978 	else
979 		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
980 	/* Command area. */
981 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
982 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
983 	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
984 	    0, NULL, NULL, &ch->dma.work_tag))
985 		goto error;
986 	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
987 	    &ch->dma.work_map))
988 		goto error;
989 	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
990 	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
991 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
992 		goto error;
993 	}
994 	ch->dma.work_bus = dcba.maddr;
995 	/* FIS receive area. */
996 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 4096, 0,
997 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
998 	    NULL, NULL, 4096, 1, 4096,
999 	    0, NULL, NULL, &ch->dma.rfis_tag))
1000 		goto error;
1001 	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1002 	    &ch->dma.rfis_map))
1003 		goto error;
1004 	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1005 	    4096, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1006 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1007 		goto error;
1008 	}
1009 	ch->dma.rfis_bus = dcba.maddr;
1010 	/* Data area. */
1011 	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1012 	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1013 	    NULL, NULL,
1014 	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1015 	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1016 	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1017 		goto error;
1018 	}
1019 	return;
1020 
1021 error:
1022 	device_printf(dev, "WARNING - DMA initialization failed\n");
1023 	ahci_dmafini(dev);
1024 }
1025 
1026 static void
1027 ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1028 {
1029 	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1030 
1031 	if (!(dcba->error = error))
1032 		dcba->maddr = segs[0].ds_addr;
1033 }
1034 
1035 static void
1036 ahci_dmafini(device_t dev)
1037 {
1038 	struct ahci_channel *ch = device_get_softc(dev);
1039 
1040 	if (ch->dma.data_tag) {
1041 		bus_dma_tag_destroy(ch->dma.data_tag);
1042 		ch->dma.data_tag = NULL;
1043 	}
1044 	if (ch->dma.rfis_bus) {
1045 		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1046 		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1047 		ch->dma.rfis_bus = 0;
1048 		ch->dma.rfis_map = NULL;
1049 		ch->dma.rfis = NULL;
1050 	}
1051 	if (ch->dma.work_bus) {
1052 		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1053 		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1054 		ch->dma.work_bus = 0;
1055 		ch->dma.work_map = NULL;
1056 		ch->dma.work = NULL;
1057 	}
1058 	if (ch->dma.work_tag) {
1059 		bus_dma_tag_destroy(ch->dma.work_tag);
1060 		ch->dma.work_tag = NULL;
1061 	}
1062 }
1063 
1064 static void
1065 ahci_slotsalloc(device_t dev)
1066 {
1067 	struct ahci_channel *ch = device_get_softc(dev);
1068 	int i;
1069 
1070 	/* Alloc and setup command/dma slots */
1071 	bzero(ch->slot, sizeof(ch->slot));
1072 	for (i = 0; i < ch->numslots; i++) {
1073 		struct ahci_slot *slot = &ch->slot[i];
1074 
1075 		slot->dev = dev;
1076 		slot->slot = i;
1077 		slot->state = AHCI_SLOT_EMPTY;
1078 		slot->ccb = NULL;
1079 		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1080 
1081 		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1082 			device_printf(ch->dev, "FAILURE - create data_map\n");
1083 	}
1084 }
1085 
1086 static void
1087 ahci_slotsfree(device_t dev)
1088 {
1089 	struct ahci_channel *ch = device_get_softc(dev);
1090 	int i;
1091 
1092 	/* Free all dma slots */
1093 	for (i = 0; i < ch->numslots; i++) {
1094 		struct ahci_slot *slot = &ch->slot[i];
1095 
1096 		callout_drain(&slot->timeout);
1097 		if (slot->dma.data_map) {
1098 			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1099 			slot->dma.data_map = NULL;
1100 		}
1101 	}
1102 }
1103 
1104 static void
1105 ahci_phy_check_events(device_t dev, u_int32_t serr)
1106 {
1107 	struct ahci_channel *ch = device_get_softc(dev);
1108 
1109 	if ((serr & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
1110 		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1111 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1112 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1113 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
1114 			if (bootverbose)
1115 				device_printf(dev, "CONNECT requested\n");
1116 			ahci_reset(dev);
1117 		} else {
1118 			if (bootverbose)
1119 				device_printf(dev, "DISCONNECT requested\n");
1120 			ch->devices = 0;
1121 		}
1122 	}
1123 }
1124 
1125 static void
1126 ahci_notify_events(device_t dev, u_int32_t status)
1127 {
1128 	struct ahci_channel *ch = device_get_softc(dev);
1129 	struct cam_path *dpath;
1130 	int i;
1131 
1132 	if (ch->caps & AHCI_CAP_SSNTF)
1133 		ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1134 	if (bootverbose)
1135 		device_printf(dev, "SNTF 0x%04x\n", status);
1136 	for (i = 0; i < 16; i++) {
1137 		if ((status & (1 << i)) == 0)
1138 			continue;
1139 		if (xpt_create_path(&dpath, NULL,
1140 		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1141 			xpt_async(AC_SCSI_AEN, dpath, NULL);
1142 			xpt_free_path(dpath);
1143 		}
1144 	}
1145 }
1146 
1147 static void
1148 ahci_ch_intr_locked(void *data)
1149 {
1150 	device_t dev = (device_t)data;
1151 	struct ahci_channel *ch = device_get_softc(dev);
1152 
1153 	mtx_lock(&ch->mtx);
1154 	ahci_ch_intr(data);
1155 	mtx_unlock(&ch->mtx);
1156 }
1157 
1158 static void
1159 ahci_ch_pm(void *arg)
1160 {
1161 	device_t dev = (device_t)arg;
1162 	struct ahci_channel *ch = device_get_softc(dev);
1163 	uint32_t work;
1164 
1165 	if (ch->numrslots != 0)
1166 		return;
1167 	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1168 	if (ch->pm_level == 4)
1169 		work |= AHCI_P_CMD_PARTIAL;
1170 	else
1171 		work |= AHCI_P_CMD_SLUMBER;
1172 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1173 }
1174 
1175 static void
1176 ahci_ch_intr(void *data)
1177 {
1178 	device_t dev = (device_t)data;
1179 	struct ahci_channel *ch = device_get_softc(dev);
1180 	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1181 	enum ahci_err_type et;
1182 	int i, ccs, ncq_err = 0;
1183 
1184 	/* Read and clear interrupt statuses. */
1185 	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1186 	if (istatus == 0)
1187 		return;
1188 	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1189 	/* Read command statuses. */
1190 	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1191 	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1192 	if (istatus & AHCI_P_IX_SDB) {
1193 		if (ch->caps & AHCI_CAP_SSNTF)
1194 			sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1195 		else {
1196 			u_int8_t *fis = ch->dma.rfis + 0x58;
1197 
1198 			if (fis[1] & 0x80)
1199 				sntf = (1 << (fis[1] & 0x0f));
1200 		}
1201 	}
1202 	/* Process PHY events */
1203 	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1204 	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1205 		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1206 		if (serr) {
1207 			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1208 			ahci_phy_check_events(dev, serr);
1209 		}
1210 	}
1211 	/* Process command errors */
1212 	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1213 	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1214 //device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1215 //    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1216 //    serr);
1217 		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1218 		    >> AHCI_P_CMD_CCS_SHIFT;
1219 		err = ch->rslots & (cstatus | sstatus);
1220 		/* Kick controller into sane state */
1221 		ahci_stop(dev);
1222 		ahci_start(dev);
1223 	} else {
1224 		ccs = 0;
1225 		err = 0;
1226 	}
1227 	/* Complete all successfull commands. */
1228 	ok = ch->rslots & ~(cstatus | sstatus);
1229 	for (i = 0; i < ch->numslots; i++) {
1230 		if ((ok >> i) & 1)
1231 			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1232 	}
1233 	/* On error, complete the rest of commands with error statuses. */
1234 	if (err) {
1235 		if (ch->frozen) {
1236 			union ccb *fccb = ch->frozen;
1237 			ch->frozen = NULL;
1238 			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1239 			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1240 				xpt_freeze_devq(fccb->ccb_h.path, 1);
1241 				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1242 			}
1243 			xpt_done(fccb);
1244 		}
1245 		for (i = 0; i < ch->numslots; i++) {
1246 			/* XXX: reqests in loading state. */
1247 			if (((err >> i) & 1) == 0)
1248 				continue;
1249 			if (istatus & AHCI_P_IX_TFE) {
1250 				/* Task File Error */
1251 				if (ch->numtslots == 0) {
1252 					/* Untagged operation. */
1253 					if (i == ccs)
1254 						et = AHCI_ERR_TFE;
1255 					else
1256 						et = AHCI_ERR_INNOCENT;
1257 				} else {
1258 					/* Tagged operation. */
1259 					et = AHCI_ERR_NCQ;
1260 					ncq_err = 1;
1261 				}
1262 			} else if (istatus & AHCI_P_IX_IF) {
1263 				if (ch->numtslots == 0 && i != ccs)
1264 					et = AHCI_ERR_INNOCENT;
1265 				else
1266 					et = AHCI_ERR_SATA;
1267 			} else
1268 				et = AHCI_ERR_INVALID;
1269 			ahci_end_transaction(&ch->slot[i], et);
1270 		}
1271 		if (ncq_err)
1272 			ahci_issue_read_log(dev);
1273 	}
1274 	/* Process NOTIFY events */
1275 	if (sntf)
1276 		ahci_notify_events(dev, sntf);
1277 }
1278 
1279 /* Must be called with channel locked. */
1280 static int
1281 ahci_check_collision(device_t dev, union ccb *ccb)
1282 {
1283 	struct ahci_channel *ch = device_get_softc(dev);
1284 
1285 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1286 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1287 		/* Tagged command while untagged are active. */
1288 		if (ch->numrslots != 0 && ch->numtslots == 0)
1289 			return (1);
1290 		/* Tagged command while tagged to other target is active. */
1291 		if (ch->numtslots != 0 &&
1292 		    ch->taggedtarget != ccb->ccb_h.target_id)
1293 			return (1);
1294 		/* Tagged command while we have no supported tag free. */
1295 		if (((~ch->oslots) & (0xffffffff >> (32 -
1296 		    ch->curr[ccb->ccb_h.target_id].tags))) == 0)
1297 			return (1);
1298 	} else {
1299 		/* Untagged command while tagged are active. */
1300 		if (ch->numrslots != 0 && ch->numtslots != 0)
1301 			return (1);
1302 	}
1303 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1304 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1305 		/* Atomic command while anything active. */
1306 		if (ch->numrslots != 0)
1307 			return (1);
1308 	}
1309        /* We have some atomic command running. */
1310        if (ch->aslots != 0)
1311                return (1);
1312 	return (0);
1313 }
1314 
1315 /* Must be called with channel locked. */
1316 static void
1317 ahci_begin_transaction(device_t dev, union ccb *ccb)
1318 {
1319 	struct ahci_channel *ch = device_get_softc(dev);
1320 	struct ahci_slot *slot;
1321 	int tag, tags;
1322 
1323 	/* Choose empty slot. */
1324 	tags = ch->numslots;
1325 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1326 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1327 		tags = ch->curr[ccb->ccb_h.target_id].tags;
1328 	tag = ch->lastslot;
1329 	while (1) {
1330 		if (tag >= tags)
1331 			tag = 0;
1332 		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1333 			break;
1334 		tag++;
1335 	};
1336 	ch->lastslot = tag;
1337 	/* Occupy chosen slot. */
1338 	slot = &ch->slot[tag];
1339 	slot->ccb = ccb;
1340 	/* Stop PM timer. */
1341 	if (ch->numrslots == 0 && ch->pm_level > 3)
1342 		callout_stop(&ch->pm_timer);
1343 	/* Update channel stats. */
1344 	ch->oslots |= (1 << slot->slot);
1345 	ch->numrslots++;
1346 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1347 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1348 		ch->numtslots++;
1349 		ch->taggedtarget = ccb->ccb_h.target_id;
1350 	}
1351 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1352 	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1353 		ch->aslots |= (1 << slot->slot);
1354 	slot->dma.nsegs = 0;
1355 	/* If request moves data, setup and load SG list */
1356 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1357 		void *buf;
1358 		bus_size_t size;
1359 
1360 		slot->state = AHCI_SLOT_LOADING;
1361 		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1362 			buf = ccb->ataio.data_ptr;
1363 			size = ccb->ataio.dxfer_len;
1364 		} else {
1365 			buf = ccb->csio.data_ptr;
1366 			size = ccb->csio.dxfer_len;
1367 		}
1368 		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1369 		    buf, size, ahci_dmasetprd, slot, 0);
1370 	} else
1371 		ahci_execute_transaction(slot);
1372 }
1373 
1374 /* Locked by busdma engine. */
1375 static void
1376 ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1377 {
1378 	struct ahci_slot *slot = arg;
1379 	struct ahci_channel *ch = device_get_softc(slot->dev);
1380 	struct ahci_cmd_tab *ctp;
1381 	struct ahci_dma_prd *prd;
1382 	int i;
1383 
1384 	if (error) {
1385 		device_printf(slot->dev, "DMA load error\n");
1386 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1387 		return;
1388 	}
1389 	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1390 	/* Get a piece of the workspace for this request */
1391 	ctp = (struct ahci_cmd_tab *)
1392 		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1393 	/* Fill S/G table */
1394 	prd = &ctp->prd_tab[0];
1395 	for (i = 0; i < nsegs; i++) {
1396 		prd[i].dba = htole64(segs[i].ds_addr);
1397 		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1398 	}
1399 	slot->dma.nsegs = nsegs;
1400 	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1401 	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1402 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1403 	ahci_execute_transaction(slot);
1404 }
1405 
1406 /* Must be called with channel locked. */
1407 static void
1408 ahci_execute_transaction(struct ahci_slot *slot)
1409 {
1410 	device_t dev = slot->dev;
1411 	struct ahci_channel *ch = device_get_softc(dev);
1412 	struct ahci_cmd_tab *ctp;
1413 	struct ahci_cmd_list *clp;
1414 	union ccb *ccb = slot->ccb;
1415 	int port = ccb->ccb_h.target_id & 0x0f;
1416 	int fis_size;
1417 
1418 	/* Get a piece of the workspace for this request */
1419 	ctp = (struct ahci_cmd_tab *)
1420 		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1421 	/* Setup the FIS for this request */
1422 	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1423 		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1424 		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1425 		return;
1426 	}
1427 	/* Setup the command list entry */
1428 	clp = (struct ahci_cmd_list *)
1429 	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1430 	clp->prd_length = slot->dma.nsegs;
1431 	clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1432 		     (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1433 		      (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1434 		     (fis_size / sizeof(u_int32_t)) |
1435 		     (port << 12);
1436 	/* Special handling for Soft Reset command. */
1437 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1438 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1439 	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1440 		/* Kick controller into sane state */
1441 		ahci_stop(dev);
1442 		ahci_clo(dev);
1443 		ahci_start(dev);
1444 		clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1445 	}
1446 	clp->bytecount = 0;
1447 	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1448 				  (AHCI_CT_SIZE * slot->slot));
1449 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1450 	    BUS_DMASYNC_PREWRITE);
1451 	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1452 	    BUS_DMASYNC_PREREAD);
1453 	/* Set ACTIVE bit for NCQ commands. */
1454 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1455 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1456 		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1457 	}
1458 	/* Issue command to the controller. */
1459 	slot->state = AHCI_SLOT_RUNNING;
1460 	ch->rslots |= (1 << slot->slot);
1461 	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1462 	/* Device reset commands doesn't interrupt. Poll them. */
1463 	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1464 	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1465 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1466 		int count, timeout = ccb->ccb_h.timeout;
1467 		enum ahci_err_type et = AHCI_ERR_NONE;
1468 
1469 		for (count = 0; count < timeout; count++) {
1470 			DELAY(1000);
1471 			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1472 				break;
1473 			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1474 				device_printf(ch->dev,
1475 				    "Poll error on slot %d, TFD: %04x\n",
1476 				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1477 				et = AHCI_ERR_TFE;
1478 				break;
1479 			}
1480 			/* Workaround for ATI SB600/SB700 chipsets. */
1481 			if (ccb->ccb_h.target_id == 15 &&
1482 			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1483 			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1484 				et = AHCI_ERR_TIMEOUT;
1485 				break;
1486 			}
1487 		}
1488 		if (timeout && (count >= timeout)) {
1489 			device_printf(ch->dev,
1490 			    "Poll timeout on slot %d\n", slot->slot);
1491 			et = AHCI_ERR_TIMEOUT;
1492 		}
1493 		if (et != AHCI_ERR_NONE) {
1494 			/* Kick controller into sane state */
1495 			ahci_stop(ch->dev);
1496 			ahci_start(ch->dev);
1497 		}
1498 		ahci_end_transaction(slot, et);
1499 		return;
1500 	}
1501 	/* Start command execution timeout */
1502 	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1503 	    (timeout_t*)ahci_timeout, slot);
1504 	return;
1505 }
1506 
1507 /* Locked by callout mechanism. */
1508 static void
1509 ahci_timeout(struct ahci_slot *slot)
1510 {
1511 	device_t dev = slot->dev;
1512 	struct ahci_channel *ch = device_get_softc(dev);
1513 	uint32_t sstatus;
1514 	int ccs;
1515 	int i;
1516 
1517 	/* Check for stale timeout. */
1518 	if (slot->state < AHCI_SLOT_RUNNING)
1519 		return;
1520 
1521 	/* Check if slot was not being executed last time we checked. */
1522 	if (slot->state < AHCI_SLOT_EXECUTING) {
1523 		/* Check if slot started executing. */
1524 		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1525 		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1526 		    >> AHCI_P_CMD_CCS_SHIFT;
1527 		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot)
1528 			slot->state = AHCI_SLOT_EXECUTING;
1529 
1530 		callout_reset(&slot->timeout,
1531 		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1532 		    (timeout_t*)ahci_timeout, slot);
1533 		return;
1534 	}
1535 
1536 	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1537 	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1538 	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1539 	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1540 	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1541 
1542 	ch->fatalerr = 1;
1543 	/* Handle frozen command. */
1544 	if (ch->frozen) {
1545 		union ccb *fccb = ch->frozen;
1546 		ch->frozen = NULL;
1547 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1548 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1549 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1550 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1551 		}
1552 		xpt_done(fccb);
1553 	}
1554 	/* Handle command with timeout. */
1555 	ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1556 	/* Handle the rest of commands. */
1557 	for (i = 0; i < ch->numslots; i++) {
1558 		/* Do we have a running request on slot? */
1559 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1560 			continue;
1561 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1562 	}
1563 }
1564 
1565 /* Must be called with channel locked. */
1566 static void
1567 ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1568 {
1569 	device_t dev = slot->dev;
1570 	struct ahci_channel *ch = device_get_softc(dev);
1571 	union ccb *ccb = slot->ccb;
1572 
1573 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1574 	    BUS_DMASYNC_POSTWRITE);
1575 	/* Read result registers to the result struct
1576 	 * May be incorrect if several commands finished same time,
1577 	 * so read only when sure or have to.
1578 	 */
1579 	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1580 		struct ata_res *res = &ccb->ataio.res;
1581 
1582 		if ((et == AHCI_ERR_TFE) ||
1583 		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1584 			u_int8_t *fis = ch->dma.rfis + 0x40;
1585 			uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1586 
1587 			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1588 			    BUS_DMASYNC_POSTREAD);
1589 			res->status = tfd;
1590 			res->error = tfd >> 8;
1591 			res->lba_low = fis[4];
1592 			res->lba_mid = fis[5];
1593 			res->lba_high = fis[6];
1594 			res->device = fis[7];
1595 			res->lba_low_exp = fis[8];
1596 			res->lba_mid_exp = fis[9];
1597 			res->lba_high_exp = fis[10];
1598 			res->sector_count = fis[12];
1599 			res->sector_count_exp = fis[13];
1600 		} else
1601 			bzero(res, sizeof(*res));
1602 	}
1603 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1604 		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1605 		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1606 		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1607 		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1608 	}
1609 	/* In case of error, freeze device for proper recovery. */
1610 	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1611 	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1612 		xpt_freeze_devq(ccb->ccb_h.path, 1);
1613 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1614 	}
1615 	/* Set proper result status. */
1616 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1617 	switch (et) {
1618 	case AHCI_ERR_NONE:
1619 		ccb->ccb_h.status |= CAM_REQ_CMP;
1620 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1621 			ccb->csio.scsi_status = SCSI_STATUS_OK;
1622 		break;
1623 	case AHCI_ERR_INVALID:
1624 		ch->fatalerr = 1;
1625 		ccb->ccb_h.status |= CAM_REQ_INVALID;
1626 		break;
1627 	case AHCI_ERR_INNOCENT:
1628 		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1629 		break;
1630 	case AHCI_ERR_TFE:
1631 	case AHCI_ERR_NCQ:
1632 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1633 			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1634 			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1635 		} else {
1636 			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1637 		}
1638 		break;
1639 	case AHCI_ERR_SATA:
1640 		ch->fatalerr = 1;
1641 		if (!ch->readlog) {
1642 			xpt_freeze_simq(ch->sim, 1);
1643 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1644 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1645 		}
1646 		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1647 		break;
1648 	case AHCI_ERR_TIMEOUT:
1649 		/* Do no treat soft-reset timeout as fatal here. */
1650 		if (ccb->ccb_h.func_code != XPT_ATA_IO ||
1651 	            !(ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))
1652 			ch->fatalerr = 1;
1653 		if (!ch->readlog) {
1654 			xpt_freeze_simq(ch->sim, 1);
1655 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1656 			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1657 		}
1658 		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1659 		break;
1660 	default:
1661 		ch->fatalerr = 1;
1662 		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1663 	}
1664 	/* Free slot. */
1665 	ch->oslots &= ~(1 << slot->slot);
1666 	ch->rslots &= ~(1 << slot->slot);
1667 	ch->aslots &= ~(1 << slot->slot);
1668 	slot->state = AHCI_SLOT_EMPTY;
1669 	slot->ccb = NULL;
1670 	/* Update channel stats. */
1671 	ch->numrslots--;
1672 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1673 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1674 		ch->numtslots--;
1675 	}
1676 	/* If it was first request of reset sequence and there is no error,
1677 	 * proceed to second request. */
1678 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1679 	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1680 	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1681 	    et == AHCI_ERR_NONE) {
1682 		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1683 		ahci_begin_transaction(dev, ccb);
1684 		return;
1685 	}
1686 	/* If it was our READ LOG command - process it. */
1687 	if (ch->readlog) {
1688 		ahci_process_read_log(dev, ccb);
1689 	/* If it was NCQ command error, put result on hold. */
1690 	} else if (et == AHCI_ERR_NCQ) {
1691 		ch->hold[slot->slot] = ccb;
1692 	} else
1693 		xpt_done(ccb);
1694 	/* Unfreeze frozen command. */
1695 	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
1696 		union ccb *fccb = ch->frozen;
1697 		ch->frozen = NULL;
1698 		ahci_begin_transaction(dev, fccb);
1699 		xpt_release_simq(ch->sim, TRUE);
1700 	}
1701 	/* If we have no other active commands, ... */
1702 	if (ch->rslots == 0) {
1703 		/* if there was fatal error - reset port. */
1704 		if (ch->fatalerr) {
1705 			ahci_reset(dev);
1706 		}
1707 	}
1708 	/* Start PM timer. */
1709 	if (ch->numrslots == 0 && ch->pm_level > 3) {
1710 		callout_schedule(&ch->pm_timer,
1711 		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1712 	}
1713 }
1714 
1715 static void
1716 ahci_issue_read_log(device_t dev)
1717 {
1718 	struct ahci_channel *ch = device_get_softc(dev);
1719 	union ccb *ccb;
1720 	struct ccb_ataio *ataio;
1721 	int i;
1722 
1723 	ch->readlog = 1;
1724 	/* Find some holden command. */
1725 	for (i = 0; i < ch->numslots; i++) {
1726 		if (ch->hold[i])
1727 			break;
1728 	}
1729 	ccb = xpt_alloc_ccb_nowait();
1730 	if (ccb == NULL) {
1731 		device_printf(dev, "Unable allocate READ LOG command");
1732 		return; /* XXX */
1733 	}
1734 	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1735 	ccb->ccb_h.func_code = XPT_ATA_IO;
1736 	ccb->ccb_h.flags = CAM_DIR_IN;
1737 	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1738 	ataio = &ccb->ataio;
1739 	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1740 	if (ataio->data_ptr == NULL) {
1741 		device_printf(dev, "Unable allocate memory for READ LOG command");
1742 		return; /* XXX */
1743 	}
1744 	ataio->dxfer_len = 512;
1745 	bzero(&ataio->cmd, sizeof(ataio->cmd));
1746 	ataio->cmd.flags = CAM_ATAIO_48BIT;
1747 	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1748 	ataio->cmd.sector_count = 1;
1749 	ataio->cmd.sector_count_exp = 0;
1750 	ataio->cmd.lba_low = 0x10;
1751 	ataio->cmd.lba_mid = 0;
1752 	ataio->cmd.lba_mid_exp = 0;
1753 	/* Freeze SIM while doing READ LOG EXT. */
1754 	xpt_freeze_simq(ch->sim, 1);
1755 	ahci_begin_transaction(dev, ccb);
1756 }
1757 
1758 static void
1759 ahci_process_read_log(device_t dev, union ccb *ccb)
1760 {
1761 	struct ahci_channel *ch = device_get_softc(dev);
1762 	uint8_t *data;
1763 	struct ata_res *res;
1764 	int i;
1765 
1766 	ch->readlog = 0;
1767 
1768 	data = ccb->ataio.data_ptr;
1769 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1770 	    (data[0] & 0x80) == 0) {
1771 		for (i = 0; i < ch->numslots; i++) {
1772 			if (!ch->hold[i])
1773 				continue;
1774 			if ((data[0] & 0x1F) == i) {
1775 				res = &ch->hold[i]->ataio.res;
1776 				res->status = data[2];
1777 				res->error = data[3];
1778 				res->lba_low = data[4];
1779 				res->lba_mid = data[5];
1780 				res->lba_high = data[6];
1781 				res->device = data[7];
1782 				res->lba_low_exp = data[8];
1783 				res->lba_mid_exp = data[9];
1784 				res->lba_high_exp = data[10];
1785 				res->sector_count = data[12];
1786 				res->sector_count_exp = data[13];
1787 			} else {
1788 				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1789 				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1790 			}
1791 			xpt_done(ch->hold[i]);
1792 			ch->hold[i] = NULL;
1793 		}
1794 	} else {
1795 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1796 			device_printf(dev, "Error while READ LOG EXT\n");
1797 		else if ((data[0] & 0x80) == 0) {
1798 			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1799 		}
1800 		for (i = 0; i < ch->numslots; i++) {
1801 			if (!ch->hold[i])
1802 				continue;
1803 			xpt_done(ch->hold[i]);
1804 			ch->hold[i] = NULL;
1805 		}
1806 	}
1807 	free(ccb->ataio.data_ptr, M_AHCI);
1808 	xpt_free_ccb(ccb);
1809 	xpt_release_simq(ch->sim, TRUE);
1810 }
1811 
1812 static void
1813 ahci_start(device_t dev)
1814 {
1815 	struct ahci_channel *ch = device_get_softc(dev);
1816 	u_int32_t cmd;
1817 
1818 	/* Clear SATA error register */
1819 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
1820 	/* Clear any interrupts pending on this channel */
1821 	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
1822 	/* Start operations on this channel */
1823 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1824 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
1825 	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
1826 }
1827 
1828 static void
1829 ahci_stop(device_t dev)
1830 {
1831 	struct ahci_channel *ch = device_get_softc(dev);
1832 	u_int32_t cmd;
1833 	int timeout;
1834 
1835 	/* Kill all activity on this channel */
1836 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1837 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
1838 	/* Wait for activity stop. */
1839 	timeout = 0;
1840 	do {
1841 		DELAY(1000);
1842 		if (timeout++ > 1000) {
1843 			device_printf(dev, "stopping AHCI engine failed\n");
1844 			break;
1845 		}
1846 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
1847 }
1848 
1849 static void
1850 ahci_clo(device_t dev)
1851 {
1852 	struct ahci_channel *ch = device_get_softc(dev);
1853 	u_int32_t cmd;
1854 	int timeout;
1855 
1856 	/* Issue Command List Override if supported */
1857 	if (ch->caps & AHCI_CAP_SCLO) {
1858 		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1859 		cmd |= AHCI_P_CMD_CLO;
1860 		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
1861 		timeout = 0;
1862 		do {
1863 			DELAY(1000);
1864 			if (timeout++ > 1000) {
1865 			    device_printf(dev, "executing CLO failed\n");
1866 			    break;
1867 			}
1868 		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
1869 	}
1870 }
1871 
1872 static void
1873 ahci_stop_fr(device_t dev)
1874 {
1875 	struct ahci_channel *ch = device_get_softc(dev);
1876 	u_int32_t cmd;
1877 	int timeout;
1878 
1879 	/* Kill all FIS reception on this channel */
1880 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1881 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
1882 	/* Wait for FIS reception stop. */
1883 	timeout = 0;
1884 	do {
1885 		DELAY(1000);
1886 		if (timeout++ > 1000) {
1887 			device_printf(dev, "stopping AHCI FR engine failed\n");
1888 			break;
1889 		}
1890 	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
1891 }
1892 
1893 static void
1894 ahci_start_fr(device_t dev)
1895 {
1896 	struct ahci_channel *ch = device_get_softc(dev);
1897 	u_int32_t cmd;
1898 
1899 	/* Start FIS reception on this channel */
1900 	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1901 	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
1902 }
1903 
1904 static int
1905 ahci_wait_ready(device_t dev, int t)
1906 {
1907 	struct ahci_channel *ch = device_get_softc(dev);
1908 	int timeout = 0;
1909 	uint32_t val;
1910 
1911 	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
1912 	    (ATA_S_BUSY | ATA_S_DRQ)) {
1913 		DELAY(1000);
1914 		if (timeout++ > t) {
1915 			device_printf(dev, "port is not ready (timeout %dms) "
1916 			    "tfd = %08x\n", t, val);
1917 			return (EBUSY);
1918 		}
1919 	}
1920 	if (bootverbose)
1921 		device_printf(dev, "ready wait time=%dms\n", timeout);
1922 	return (0);
1923 }
1924 
1925 static void
1926 ahci_reset(device_t dev)
1927 {
1928 	struct ahci_channel *ch = device_get_softc(dev);
1929 	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
1930 	int i;
1931 
1932 	if (bootverbose)
1933 		device_printf(dev, "AHCI reset...\n");
1934 	/* Requeue freezed command. */
1935 	if (ch->frozen) {
1936 		union ccb *fccb = ch->frozen;
1937 		ch->frozen = NULL;
1938 		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1939 		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1940 			xpt_freeze_devq(fccb->ccb_h.path, 1);
1941 			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1942 		}
1943 		xpt_done(fccb);
1944 	}
1945 	/* Kill the engine and requeue all running commands. */
1946 	ahci_stop(dev);
1947 	for (i = 0; i < ch->numslots; i++) {
1948 		/* Do we have a running request on slot? */
1949 		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1950 			continue;
1951 		/* XXX; Commands in loading state. */
1952 		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1953 	}
1954 	for (i = 0; i < ch->numslots; i++) {
1955 		if (!ch->hold[i])
1956 			continue;
1957 		xpt_done(ch->hold[i]);
1958 		ch->hold[i] = NULL;
1959 	}
1960 	ch->fatalerr = 0;
1961 	/* Tell the XPT about the event */
1962 	xpt_async(AC_BUS_RESET, ch->path, NULL);
1963 	/* Disable port interrupts */
1964 	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1965 	/* Reset and reconnect PHY, */
1966 	if (!ahci_sata_phy_reset(dev, 0)) {
1967 		if (bootverbose)
1968 			device_printf(dev,
1969 			    "AHCI reset done: phy reset found no device\n");
1970 		ch->devices = 0;
1971 		/* Enable wanted port interrupts */
1972 		ATA_OUTL(ch->r_mem, AHCI_P_IE,
1973 		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
1974 		return;
1975 	}
1976 	/* Wait for clearing busy status. */
1977 	if (ahci_wait_ready(dev, 10000)) {
1978 		device_printf(dev, "device ready timeout\n");
1979 		ahci_clo(dev);
1980 	}
1981 	ahci_start(dev);
1982 	ch->devices = 1;
1983 	/* Enable wanted port interrupts */
1984 	ATA_OUTL(ch->r_mem, AHCI_P_IE,
1985 	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
1986 	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
1987 	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
1988 	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
1989 	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
1990 	if (bootverbose)
1991 		device_printf(dev, "AHCI reset done: device found\n");
1992 }
1993 
1994 static int
1995 ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
1996 {
1997 	struct ahci_channel *ch = device_get_softc(dev);
1998 	u_int8_t *fis = &ctp->cfis[0];
1999 
2000 	bzero(ctp->cfis, 64);
2001 	fis[0] = 0x27;  		/* host to device */
2002 	fis[1] = (ccb->ccb_h.target_id & 0x0f);
2003 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2004 		fis[1] |= 0x80;
2005 		fis[2] = ATA_PACKET_CMD;
2006 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
2007 		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
2008 			fis[3] = ATA_F_DMA;
2009 		else {
2010 			fis[5] = ccb->csio.dxfer_len;
2011 		        fis[6] = ccb->csio.dxfer_len >> 8;
2012 		}
2013 		fis[7] = ATA_D_LBA;
2014 		fis[15] = ATA_A_4BIT;
2015 		bzero(ctp->acmd, 32);
2016 		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2017 		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2018 		    ctp->acmd, ccb->csio.cdb_len);
2019 	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2020 		fis[1] |= 0x80;
2021 		fis[2] = ccb->ataio.cmd.command;
2022 		fis[3] = ccb->ataio.cmd.features;
2023 		fis[4] = ccb->ataio.cmd.lba_low;
2024 		fis[5] = ccb->ataio.cmd.lba_mid;
2025 		fis[6] = ccb->ataio.cmd.lba_high;
2026 		fis[7] = ccb->ataio.cmd.device;
2027 		fis[8] = ccb->ataio.cmd.lba_low_exp;
2028 		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2029 		fis[10] = ccb->ataio.cmd.lba_high_exp;
2030 		fis[11] = ccb->ataio.cmd.features_exp;
2031 		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2032 			fis[12] = tag << 3;
2033 			fis[13] = 0;
2034 		} else {
2035 			fis[12] = ccb->ataio.cmd.sector_count;
2036 			fis[13] = ccb->ataio.cmd.sector_count_exp;
2037 		}
2038 		fis[15] = ATA_A_4BIT;
2039 	} else {
2040 		fis[15] = ccb->ataio.cmd.control;
2041 	}
2042 	return (20);
2043 }
2044 
2045 static int
2046 ahci_sata_connect(struct ahci_channel *ch)
2047 {
2048 	u_int32_t status;
2049 	int timeout;
2050 
2051 	/* Wait up to 100ms for "connect well" */
2052 	for (timeout = 0; timeout < 100 ; timeout++) {
2053 		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2054 		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2055 		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2056 		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2057 			break;
2058 		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2059 			if (bootverbose) {
2060 				device_printf(ch->dev, "SATA offline status=%08x\n",
2061 				    status);
2062 			}
2063 			return (0);
2064 		}
2065 		DELAY(1000);
2066 	}
2067 	if (timeout >= 100) {
2068 		if (bootverbose) {
2069 			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2070 			    status);
2071 		}
2072 		return (0);
2073 	}
2074 	if (bootverbose) {
2075 		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2076 		    timeout, status);
2077 	}
2078 	/* Clear SATA error register */
2079 	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2080 	return (1);
2081 }
2082 
2083 static int
2084 ahci_sata_phy_reset(device_t dev, int quick)
2085 {
2086 	struct ahci_channel *ch = device_get_softc(dev);
2087 	int sata_rev;
2088 	uint32_t val;
2089 
2090 	if (quick) {
2091 		val = ATA_INL(ch->r_mem, AHCI_P_SCTL);
2092 		if ((val & ATA_SC_DET_MASK) == ATA_SC_DET_IDLE)
2093 			return (ahci_sata_connect(ch));
2094 	}
2095 
2096 	if (bootverbose)
2097 		device_printf(dev, "hardware reset ...\n");
2098 	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2099 	if (sata_rev == 1)
2100 		val = ATA_SC_SPD_SPEED_GEN1;
2101 	else if (sata_rev == 2)
2102 		val = ATA_SC_SPD_SPEED_GEN2;
2103 	else if (sata_rev == 3)
2104 		val = ATA_SC_SPD_SPEED_GEN3;
2105 	else
2106 		val = 0;
2107 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2108 	    ATA_SC_DET_RESET | val |
2109 	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2110 	DELAY(5000);
2111 	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2112 	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2113 	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2114 	DELAY(5000);
2115 	return (ahci_sata_connect(ch));
2116 }
2117 
2118 static void
2119 ahciaction(struct cam_sim *sim, union ccb *ccb)
2120 {
2121 	device_t dev;
2122 	struct ahci_channel *ch;
2123 
2124 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2125 	    ccb->ccb_h.func_code));
2126 
2127 	ch = (struct ahci_channel *)cam_sim_softc(sim);
2128 	dev = ch->dev;
2129 	switch (ccb->ccb_h.func_code) {
2130 	/* Common cases first */
2131 	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2132 	case XPT_SCSI_IO:
2133 		if (ch->devices == 0) {
2134 			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2135 			xpt_done(ccb);
2136 			break;
2137 		}
2138 		/* Check for command collision. */
2139 		if (ahci_check_collision(dev, ccb)) {
2140 			/* Freeze command. */
2141 			ch->frozen = ccb;
2142 			/* We have only one frozen slot, so freeze simq also. */
2143 			xpt_freeze_simq(ch->sim, 1);
2144 			return;
2145 		}
2146 		ahci_begin_transaction(dev, ccb);
2147 		break;
2148 	case XPT_EN_LUN:		/* Enable LUN as a target */
2149 	case XPT_TARGET_IO:		/* Execute target I/O request */
2150 	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2151 	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2152 	case XPT_ABORT:			/* Abort the specified CCB */
2153 		/* XXX Implement */
2154 		ccb->ccb_h.status = CAM_REQ_INVALID;
2155 		xpt_done(ccb);
2156 		break;
2157 	case XPT_SET_TRAN_SETTINGS:
2158 	{
2159 		struct	ccb_trans_settings *cts = &ccb->cts;
2160 		struct	ahci_device *d;
2161 
2162 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2163 			d = &ch->curr[ccb->ccb_h.target_id];
2164 		else
2165 			d = &ch->user[ccb->ccb_h.target_id];
2166 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2167 			d->revision = cts->xport_specific.sata.revision;
2168 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2169 			d->mode = cts->xport_specific.sata.mode;
2170 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2171 			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2172 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2173 			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2174 		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2175 			ch->pm_present = cts->xport_specific.sata.pm_present;
2176 		ccb->ccb_h.status = CAM_REQ_CMP;
2177 		xpt_done(ccb);
2178 		break;
2179 	}
2180 	case XPT_GET_TRAN_SETTINGS:
2181 	/* Get default/user set transfer settings for the target */
2182 	{
2183 		struct	ccb_trans_settings *cts = &ccb->cts;
2184 		struct  ahci_device *d;
2185 		uint32_t status;
2186 
2187 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2188 			d = &ch->curr[ccb->ccb_h.target_id];
2189 		else
2190 			d = &ch->user[ccb->ccb_h.target_id];
2191 		cts->protocol = PROTO_ATA;
2192 		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2193 		cts->transport = XPORT_SATA;
2194 		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2195 		cts->proto_specific.valid = 0;
2196 		cts->xport_specific.sata.valid = 0;
2197 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2198 		    (ccb->ccb_h.target_id == 15 ||
2199 		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2200 			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2201 			if (status & 0x0f0) {
2202 				cts->xport_specific.sata.revision =
2203 				    (status & 0x0f0) >> 4;
2204 				cts->xport_specific.sata.valid |=
2205 				    CTS_SATA_VALID_REVISION;
2206 			}
2207 		} else {
2208 			cts->xport_specific.sata.revision = d->revision;
2209 			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2210 		}
2211 		cts->xport_specific.sata.mode = d->mode;
2212 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2213 		cts->xport_specific.sata.bytecount = d->bytecount;
2214 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2215 		cts->xport_specific.sata.pm_present = ch->pm_present;
2216 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2217 		cts->xport_specific.sata.tags = d->tags;
2218 		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2219 		ccb->ccb_h.status = CAM_REQ_CMP;
2220 		xpt_done(ccb);
2221 		break;
2222 	}
2223 #if 0
2224 	case XPT_CALC_GEOMETRY:
2225 	{
2226 		struct	  ccb_calc_geometry *ccg;
2227 		uint32_t size_mb;
2228 		uint32_t secs_per_cylinder;
2229 
2230 		ccg = &ccb->ccg;
2231 		size_mb = ccg->volume_size
2232 			/ ((1024L * 1024L) / ccg->block_size);
2233 		if (size_mb >= 1024 && (aha->extended_trans != 0)) {
2234 			if (size_mb >= 2048) {
2235 				ccg->heads = 255;
2236 				ccg->secs_per_track = 63;
2237 			} else {
2238 				ccg->heads = 128;
2239 				ccg->secs_per_track = 32;
2240 			}
2241 		} else {
2242 			ccg->heads = 64;
2243 			ccg->secs_per_track = 32;
2244 		}
2245 		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2246 		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2247 		ccb->ccb_h.status = CAM_REQ_CMP;
2248 		xpt_done(ccb);
2249 		break;
2250 	}
2251 #endif
2252 	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2253 	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2254 		ahci_reset(dev);
2255 		ccb->ccb_h.status = CAM_REQ_CMP;
2256 		xpt_done(ccb);
2257 		break;
2258 	case XPT_TERM_IO:		/* Terminate the I/O process */
2259 		/* XXX Implement */
2260 		ccb->ccb_h.status = CAM_REQ_INVALID;
2261 		xpt_done(ccb);
2262 		break;
2263 	case XPT_PATH_INQ:		/* Path routing inquiry */
2264 	{
2265 		struct ccb_pathinq *cpi = &ccb->cpi;
2266 
2267 		cpi->version_num = 1; /* XXX??? */
2268 		cpi->hba_inquiry = PI_SDTR_ABLE;
2269 		if (ch->caps & AHCI_CAP_SNCQ)
2270 			cpi->hba_inquiry |= PI_TAG_ABLE;
2271 		if (ch->caps & AHCI_CAP_SPM)
2272 			cpi->hba_inquiry |= PI_SATAPM;
2273 		cpi->target_sprt = 0;
2274 		cpi->hba_misc = PIM_SEQSCAN;
2275 		cpi->hba_eng_cnt = 0;
2276 		if (ch->caps & AHCI_CAP_SPM)
2277 			cpi->max_target = 15;
2278 		else
2279 			cpi->max_target = 0;
2280 		cpi->max_lun = 0;
2281 		cpi->initiator_id = 0;
2282 		cpi->bus_id = cam_sim_bus(sim);
2283 		cpi->base_transfer_speed = 150000;
2284 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2285 		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2286 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2287 		cpi->unit_number = cam_sim_unit(sim);
2288 		cpi->transport = XPORT_SATA;
2289 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2290 		cpi->protocol = PROTO_ATA;
2291 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2292 		cpi->maxio = MAXPHYS;
2293 		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2294 		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
2295 			cpi->maxio = min(cpi->maxio, 128 * 512);
2296 		cpi->ccb_h.status = CAM_REQ_CMP;
2297 		xpt_done(ccb);
2298 		break;
2299 	}
2300 	default:
2301 		ccb->ccb_h.status = CAM_REQ_INVALID;
2302 		xpt_done(ccb);
2303 		break;
2304 	}
2305 }
2306 
2307 static void
2308 ahcipoll(struct cam_sim *sim)
2309 {
2310 	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2311 
2312 	ahci_ch_intr(ch->dev);
2313 }
2314