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