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