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