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