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