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