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