ahci_generic.c revision 199821
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: head/sys/dev/ahci/ahci.c 199821 2009-11-26 08:49:46Z mav $");
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 */
59static int ahci_setup_interrupt(device_t dev);
60static void ahci_intr(void *data);
61static void ahci_intr_one(void *data);
62static int ahci_suspend(device_t dev);
63static int ahci_resume(device_t dev);
64static int ahci_ch_suspend(device_t dev);
65static int ahci_ch_resume(device_t dev);
66static void ahci_ch_pm(void *arg);
67static void ahci_ch_intr_locked(void *data);
68static void ahci_ch_intr(void *data);
69static int ahci_ctlr_reset(device_t dev);
70static void ahci_begin_transaction(device_t dev, union ccb *ccb);
71static void ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
72static void ahci_execute_transaction(struct ahci_slot *slot);
73static void ahci_timeout(struct ahci_slot *slot);
74static void ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et);
75static int ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag);
76static void ahci_dmainit(device_t dev);
77static void ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error);
78static void ahci_dmafini(device_t dev);
79static void ahci_slotsalloc(device_t dev);
80static void ahci_slotsfree(device_t dev);
81static void ahci_reset(device_t dev);
82static void ahci_start(device_t dev);
83static void ahci_stop(device_t dev);
84static void ahci_clo(device_t dev);
85static void ahci_start_fr(device_t dev);
86static void ahci_stop_fr(device_t dev);
87
88static int ahci_sata_connect(struct ahci_channel *ch);
89static int ahci_sata_phy_reset(device_t dev, int quick);
90
91static void ahci_issue_read_log(device_t dev);
92static void ahci_process_read_log(device_t dev, union ccb *ccb);
93
94static void ahciaction(struct cam_sim *sim, union ccb *ccb);
95static void ahcipoll(struct cam_sim *sim);
96
97MALLOC_DEFINE(M_AHCI, "AHCI driver", "AHCI driver data buffers");
98
99static 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",	0},
119	{0x26538086, "Intel ICH6M",	0},
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
241static int
242ahci_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
273static int
274ahci_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
295static int
296ahci_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
423static int
424ahci_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
453static int
454ahci_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
500static int
501ahci_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
512static int
513ahci_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
522static int
523ahci_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	}
574	return (0);
575}
576
577/*
578 * Common case interrupt handler.
579 */
580static void
581ahci_intr(void *data)
582{
583	struct ahci_controller_irq *irq = data;
584	struct ahci_controller *ctlr = irq->ctlr;
585	u_int32_t is;
586	void *arg;
587	int unit;
588
589	if (irq->mode == AHCI_IRQ_MODE_ALL) {
590		unit = 0;
591		if (ctlr->ccc)
592			is = ctlr->ichannels;
593		else
594			is = ATA_INL(ctlr->r_mem, AHCI_IS);
595	} else {	/* AHCI_IRQ_MODE_AFTER */
596		unit = irq->r_irq_rid - 1;
597		is = ATA_INL(ctlr->r_mem, AHCI_IS);
598	}
599	for (; unit < ctlr->channels; unit++) {
600		if ((is & (1 << unit)) != 0 &&
601		    (arg = ctlr->interrupt[unit].argument)) {
602			if (ctlr->quirks & AHCI_Q_EDGEIS) {
603				/* Some controller have edge triggered IS. */
604				ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
605				ctlr->interrupt[unit].function(arg);
606			} else {
607				/* but AHCI declares level triggered IS. */
608				ctlr->interrupt[unit].function(arg);
609				ATA_OUTL(ctlr->r_mem, AHCI_IS, 1 << unit);
610			}
611		}
612	}
613}
614
615/*
616 * Simplified interrupt handler for multivector MSI mode.
617 */
618static void
619ahci_intr_one(void *data)
620{
621	struct ahci_controller_irq *irq = data;
622	struct ahci_controller *ctlr = irq->ctlr;
623	void *arg;
624	int unit;
625
626	unit = irq->r_irq_rid - 1;
627	if ((arg = ctlr->interrupt[unit].argument))
628	    ctlr->interrupt[unit].function(arg);
629}
630
631static struct resource *
632ahci_alloc_resource(device_t dev, device_t child, int type, int *rid,
633		       u_long start, u_long end, u_long count, u_int flags)
634{
635	struct ahci_controller *ctlr = device_get_softc(dev);
636	int unit = ((struct ahci_channel *)device_get_softc(child))->unit;
637	struct resource *res = NULL;
638	int offset = AHCI_OFFSET + (unit << 7);
639	long st;
640
641	switch (type) {
642	case SYS_RES_MEMORY:
643		st = rman_get_start(ctlr->r_mem);
644		res = rman_reserve_resource(&ctlr->sc_iomem, st + offset,
645		    st + offset + 127, 128, RF_ACTIVE, child);
646		if (res) {
647			bus_space_handle_t bsh;
648			bus_space_tag_t bst;
649			bsh = rman_get_bushandle(ctlr->r_mem);
650			bst = rman_get_bustag(ctlr->r_mem);
651			bus_space_subregion(bst, bsh, offset, 128, &bsh);
652			rman_set_bushandle(res, bsh);
653			rman_set_bustag(res, bst);
654		}
655		break;
656	case SYS_RES_IRQ:
657		if (*rid == ATA_IRQ_RID)
658			res = ctlr->irqs[0].r_irq;
659		break;
660	}
661	return (res);
662}
663
664static int
665ahci_release_resource(device_t dev, device_t child, int type, int rid,
666			 struct resource *r)
667{
668
669	switch (type) {
670	case SYS_RES_MEMORY:
671		rman_release_resource(r);
672		return (0);
673	case SYS_RES_IRQ:
674		if (rid != ATA_IRQ_RID)
675			return ENOENT;
676		return (0);
677	}
678	return (EINVAL);
679}
680
681static int
682ahci_setup_intr(device_t dev, device_t child, struct resource *irq,
683		   int flags, driver_filter_t *filter, driver_intr_t *function,
684		   void *argument, void **cookiep)
685{
686	struct ahci_controller *ctlr = device_get_softc(dev);
687	int unit = (intptr_t)device_get_ivars(child);
688
689	if (filter != NULL) {
690		printf("ahci.c: we cannot use a filter here\n");
691		return (EINVAL);
692	}
693	ctlr->interrupt[unit].function = function;
694	ctlr->interrupt[unit].argument = argument;
695	return (0);
696}
697
698static int
699ahci_teardown_intr(device_t dev, device_t child, struct resource *irq,
700		      void *cookie)
701{
702	struct ahci_controller *ctlr = device_get_softc(dev);
703	int unit = (intptr_t)device_get_ivars(child);
704
705	ctlr->interrupt[unit].function = NULL;
706	ctlr->interrupt[unit].argument = NULL;
707	return (0);
708}
709
710static int
711ahci_print_child(device_t dev, device_t child)
712{
713	int retval;
714
715	retval = bus_print_child_header(dev, child);
716	retval += printf(" at channel %d",
717	    (int)(intptr_t)device_get_ivars(child));
718	retval += bus_print_child_footer(dev, child);
719
720	return (retval);
721}
722
723devclass_t ahci_devclass;
724static device_method_t ahci_methods[] = {
725	DEVMETHOD(device_probe,     ahci_probe),
726	DEVMETHOD(device_attach,    ahci_attach),
727	DEVMETHOD(device_detach,    ahci_detach),
728	DEVMETHOD(device_suspend,   ahci_suspend),
729	DEVMETHOD(device_resume,    ahci_resume),
730	DEVMETHOD(bus_print_child,  ahci_print_child),
731	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
732	DEVMETHOD(bus_release_resource,     ahci_release_resource),
733	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
734	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
735	{ 0, 0 }
736};
737static driver_t ahci_driver = {
738        "ahci",
739        ahci_methods,
740        sizeof(struct ahci_controller)
741};
742DRIVER_MODULE(ahci, pci, ahci_driver, ahci_devclass, 0, 0);
743static device_method_t ahci_ata_methods[] = {
744	DEVMETHOD(device_probe,     ahci_ata_probe),
745	DEVMETHOD(device_attach,    ahci_attach),
746	DEVMETHOD(device_detach,    ahci_detach),
747	DEVMETHOD(device_suspend,   ahci_suspend),
748	DEVMETHOD(device_resume,    ahci_resume),
749	DEVMETHOD(bus_print_child,  ahci_print_child),
750	DEVMETHOD(bus_alloc_resource,       ahci_alloc_resource),
751	DEVMETHOD(bus_release_resource,     ahci_release_resource),
752	DEVMETHOD(bus_setup_intr,   ahci_setup_intr),
753	DEVMETHOD(bus_teardown_intr,ahci_teardown_intr),
754	{ 0, 0 }
755};
756static driver_t ahci_ata_driver = {
757        "ahci",
758        ahci_ata_methods,
759        sizeof(struct ahci_controller)
760};
761DRIVER_MODULE(ahci, atapci, ahci_ata_driver, ahci_devclass, 0, 0);
762MODULE_VERSION(ahci, 1);
763MODULE_DEPEND(ahci, cam, 1, 1, 1);
764
765static int
766ahci_ch_probe(device_t dev)
767{
768
769	device_set_desc_copy(dev, "AHCI channel");
770	return (0);
771}
772
773static int
774ahci_ch_attach(device_t dev)
775{
776	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
777	struct ahci_channel *ch = device_get_softc(dev);
778	struct cam_devq *devq;
779	int rid, error, i, sata_rev = 0;
780
781	ch->dev = dev;
782	ch->unit = (intptr_t)device_get_ivars(dev);
783	ch->caps = ctlr->caps;
784	ch->caps2 = ctlr->caps2;
785	ch->quirks = ctlr->quirks;
786	ch->numslots = ((ch->caps & AHCI_CAP_NCS) >> AHCI_CAP_NCS_SHIFT) + 1,
787	mtx_init(&ch->mtx, "AHCI channel lock", NULL, MTX_DEF);
788	resource_int_value(device_get_name(dev),
789	    device_get_unit(dev), "pm_level", &ch->pm_level);
790	if (ch->pm_level > 3)
791		callout_init_mtx(&ch->pm_timer, &ch->mtx, 0);
792	/* Limit speed for my onboard JMicron external port.
793	 * It is not eSATA really. */
794	if (pci_get_devid(ctlr->dev) == 0x2363197b &&
795	    pci_get_subvendor(ctlr->dev) == 0x1043 &&
796	    pci_get_subdevice(ctlr->dev) == 0x81e4 &&
797	    ch->unit == 0)
798		sata_rev = 1;
799	resource_int_value(device_get_name(dev),
800	    device_get_unit(dev), "sata_rev", &sata_rev);
801	for (i = 0; i < 16; i++) {
802		ch->user[i].revision = sata_rev;
803		ch->user[i].mode = 0;
804		ch->user[i].bytecount = 8192;
805		ch->user[i].tags = ch->numslots;
806		ch->curr[i] = ch->user[i];
807	}
808	rid = ch->unit;
809	if (!(ch->r_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
810	    &rid, RF_ACTIVE)))
811		return (ENXIO);
812	ahci_dmainit(dev);
813	ahci_slotsalloc(dev);
814	ahci_ch_resume(dev);
815	mtx_lock(&ch->mtx);
816	rid = ATA_IRQ_RID;
817	if (!(ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
818	    &rid, RF_SHAREABLE | RF_ACTIVE))) {
819		bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
820		device_printf(dev, "Unable to map interrupt\n");
821		return (ENXIO);
822	}
823	if ((bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS, NULL,
824	    ahci_ch_intr_locked, dev, &ch->ih))) {
825		device_printf(dev, "Unable to setup interrupt\n");
826		error = ENXIO;
827		goto err1;
828	}
829	/* Create the device queue for our SIM. */
830	devq = cam_simq_alloc(ch->numslots);
831	if (devq == NULL) {
832		device_printf(dev, "Unable to allocate simq\n");
833		error = ENOMEM;
834		goto err1;
835	}
836	/* Construct SIM entry */
837	ch->sim = cam_sim_alloc(ahciaction, ahcipoll, "ahcich", ch,
838	    device_get_unit(dev), &ch->mtx,
839	    min(2, ch->numslots),
840	    (ch->caps & AHCI_CAP_SNCQ) ? ch->numslots : 0,
841	    devq);
842	if (ch->sim == NULL) {
843		device_printf(dev, "unable to allocate sim\n");
844		error = ENOMEM;
845		goto err2;
846	}
847	if (xpt_bus_register(ch->sim, dev, 0) != CAM_SUCCESS) {
848		device_printf(dev, "unable to register xpt bus\n");
849		error = ENXIO;
850		goto err2;
851	}
852	if (xpt_create_path(&ch->path, /*periph*/NULL, cam_sim_path(ch->sim),
853	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
854		device_printf(dev, "unable to create path\n");
855		error = ENXIO;
856		goto err3;
857	}
858	if (ch->pm_level > 3) {
859		callout_reset(&ch->pm_timer,
860		    (ch->pm_level == 4) ? hz / 1000 : hz / 8,
861		    ahci_ch_pm, dev);
862	}
863	mtx_unlock(&ch->mtx);
864	return (0);
865
866err3:
867	xpt_bus_deregister(cam_sim_path(ch->sim));
868err2:
869	cam_sim_free(ch->sim, /*free_devq*/TRUE);
870err1:
871	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
872	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
873	mtx_unlock(&ch->mtx);
874	return (error);
875}
876
877static int
878ahci_ch_detach(device_t dev)
879{
880	struct ahci_channel *ch = device_get_softc(dev);
881
882	mtx_lock(&ch->mtx);
883	xpt_async(AC_LOST_DEVICE, ch->path, NULL);
884	xpt_free_path(ch->path);
885	xpt_bus_deregister(cam_sim_path(ch->sim));
886	cam_sim_free(ch->sim, /*free_devq*/TRUE);
887	mtx_unlock(&ch->mtx);
888
889	if (ch->pm_level > 3)
890		callout_drain(&ch->pm_timer);
891	bus_teardown_intr(dev, ch->r_irq, ch->ih);
892	bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
893
894	ahci_ch_suspend(dev);
895	ahci_slotsfree(dev);
896	ahci_dmafini(dev);
897
898	bus_release_resource(dev, SYS_RES_MEMORY, ch->unit, ch->r_mem);
899	mtx_destroy(&ch->mtx);
900	return (0);
901}
902
903static int
904ahci_ch_suspend(device_t dev)
905{
906	struct ahci_channel *ch = device_get_softc(dev);
907
908	/* Disable port interrupts. */
909	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
910	/* Reset command register. */
911	ahci_stop(dev);
912	ahci_stop_fr(dev);
913	ATA_OUTL(ch->r_mem, AHCI_P_CMD, 0);
914	/* Allow everything, including partial and slumber modes. */
915	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, 0);
916	/* Request slumber mode transition and give some time to get there. */
917	ATA_OUTL(ch->r_mem, AHCI_P_CMD, AHCI_P_CMD_SLUMBER);
918	DELAY(100);
919	/* Disable PHY. */
920	ATA_OUTL(ch->r_mem, AHCI_P_SCTL, ATA_SC_DET_DISABLE);
921	return (0);
922}
923
924static int
925ahci_ch_resume(device_t dev)
926{
927	struct ahci_channel *ch = device_get_softc(dev);
928	uint64_t work;
929
930	/* Disable port interrupts */
931	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
932	/* Setup work areas */
933	work = ch->dma.work_bus + AHCI_CL_OFFSET;
934	ATA_OUTL(ch->r_mem, AHCI_P_CLB, work & 0xffffffff);
935	ATA_OUTL(ch->r_mem, AHCI_P_CLBU, work >> 32);
936	work = ch->dma.rfis_bus;
937	ATA_OUTL(ch->r_mem, AHCI_P_FB, work & 0xffffffff);
938	ATA_OUTL(ch->r_mem, AHCI_P_FBU, work >> 32);
939	/* Activate the channel and power/spin up device */
940	ATA_OUTL(ch->r_mem, AHCI_P_CMD,
941	     (AHCI_P_CMD_ACTIVE | AHCI_P_CMD_POD | AHCI_P_CMD_SUD |
942	     ((ch->pm_level == 2 || ch->pm_level == 3) ? AHCI_P_CMD_ALPE : 0) |
943	     ((ch->pm_level > 2) ? AHCI_P_CMD_ASP : 0 )));
944	ahci_start_fr(dev);
945	ahci_start(dev);
946	return (0);
947}
948
949devclass_t ahcich_devclass;
950static device_method_t ahcich_methods[] = {
951	DEVMETHOD(device_probe,     ahci_ch_probe),
952	DEVMETHOD(device_attach,    ahci_ch_attach),
953	DEVMETHOD(device_detach,    ahci_ch_detach),
954	DEVMETHOD(device_suspend,   ahci_ch_suspend),
955	DEVMETHOD(device_resume,    ahci_ch_resume),
956	{ 0, 0 }
957};
958static driver_t ahcich_driver = {
959        "ahcich",
960        ahcich_methods,
961        sizeof(struct ahci_channel)
962};
963DRIVER_MODULE(ahcich, ahci, ahcich_driver, ahcich_devclass, 0, 0);
964
965struct ahci_dc_cb_args {
966	bus_addr_t maddr;
967	int error;
968};
969
970static void
971ahci_dmainit(device_t dev)
972{
973	struct ahci_channel *ch = device_get_softc(dev);
974	struct ahci_dc_cb_args dcba;
975
976	if (ch->caps & AHCI_CAP_64BIT)
977		ch->dma.max_address = BUS_SPACE_MAXADDR;
978	else
979		ch->dma.max_address = BUS_SPACE_MAXADDR_32BIT;
980	/* Command area. */
981	if (bus_dma_tag_create(bus_get_dma_tag(dev), 1024, 0,
982	    ch->dma.max_address, BUS_SPACE_MAXADDR,
983	    NULL, NULL, AHCI_WORK_SIZE, 1, AHCI_WORK_SIZE,
984	    0, NULL, NULL, &ch->dma.work_tag))
985		goto error;
986	if (bus_dmamem_alloc(ch->dma.work_tag, (void **)&ch->dma.work, 0,
987	    &ch->dma.work_map))
988		goto error;
989	if (bus_dmamap_load(ch->dma.work_tag, ch->dma.work_map, ch->dma.work,
990	    AHCI_WORK_SIZE, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
991		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
992		goto error;
993	}
994	ch->dma.work_bus = dcba.maddr;
995	/* FIS receive area. */
996	if (bus_dma_tag_create(bus_get_dma_tag(dev), 4096, 0,
997	    ch->dma.max_address, BUS_SPACE_MAXADDR,
998	    NULL, NULL, 4096, 1, 4096,
999	    0, NULL, NULL, &ch->dma.rfis_tag))
1000		goto error;
1001	if (bus_dmamem_alloc(ch->dma.rfis_tag, (void **)&ch->dma.rfis, 0,
1002	    &ch->dma.rfis_map))
1003		goto error;
1004	if (bus_dmamap_load(ch->dma.rfis_tag, ch->dma.rfis_map, ch->dma.rfis,
1005	    4096, ahci_dmasetupc_cb, &dcba, 0) || dcba.error) {
1006		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1007		goto error;
1008	}
1009	ch->dma.rfis_bus = dcba.maddr;
1010	/* Data area. */
1011	if (bus_dma_tag_create(bus_get_dma_tag(dev), 2, 0,
1012	    ch->dma.max_address, BUS_SPACE_MAXADDR,
1013	    NULL, NULL,
1014	    AHCI_SG_ENTRIES * PAGE_SIZE * ch->numslots,
1015	    AHCI_SG_ENTRIES, AHCI_PRD_MAX,
1016	    0, busdma_lock_mutex, &ch->mtx, &ch->dma.data_tag)) {
1017		goto error;
1018	}
1019	return;
1020
1021error:
1022	device_printf(dev, "WARNING - DMA initialization failed\n");
1023	ahci_dmafini(dev);
1024}
1025
1026static void
1027ahci_dmasetupc_cb(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
1028{
1029	struct ahci_dc_cb_args *dcba = (struct ahci_dc_cb_args *)xsc;
1030
1031	if (!(dcba->error = error))
1032		dcba->maddr = segs[0].ds_addr;
1033}
1034
1035static void
1036ahci_dmafini(device_t dev)
1037{
1038	struct ahci_channel *ch = device_get_softc(dev);
1039
1040	if (ch->dma.data_tag) {
1041		bus_dma_tag_destroy(ch->dma.data_tag);
1042		ch->dma.data_tag = NULL;
1043	}
1044	if (ch->dma.rfis_bus) {
1045		bus_dmamap_unload(ch->dma.rfis_tag, ch->dma.rfis_map);
1046		bus_dmamem_free(ch->dma.rfis_tag, ch->dma.rfis, ch->dma.rfis_map);
1047		ch->dma.rfis_bus = 0;
1048		ch->dma.rfis_map = NULL;
1049		ch->dma.rfis = NULL;
1050	}
1051	if (ch->dma.work_bus) {
1052		bus_dmamap_unload(ch->dma.work_tag, ch->dma.work_map);
1053		bus_dmamem_free(ch->dma.work_tag, ch->dma.work, ch->dma.work_map);
1054		ch->dma.work_bus = 0;
1055		ch->dma.work_map = NULL;
1056		ch->dma.work = NULL;
1057	}
1058	if (ch->dma.work_tag) {
1059		bus_dma_tag_destroy(ch->dma.work_tag);
1060		ch->dma.work_tag = NULL;
1061	}
1062}
1063
1064static void
1065ahci_slotsalloc(device_t dev)
1066{
1067	struct ahci_channel *ch = device_get_softc(dev);
1068	int i;
1069
1070	/* Alloc and setup command/dma slots */
1071	bzero(ch->slot, sizeof(ch->slot));
1072	for (i = 0; i < ch->numslots; i++) {
1073		struct ahci_slot *slot = &ch->slot[i];
1074
1075		slot->dev = dev;
1076		slot->slot = i;
1077		slot->state = AHCI_SLOT_EMPTY;
1078		slot->ccb = NULL;
1079		callout_init_mtx(&slot->timeout, &ch->mtx, 0);
1080
1081		if (bus_dmamap_create(ch->dma.data_tag, 0, &slot->dma.data_map))
1082			device_printf(ch->dev, "FAILURE - create data_map\n");
1083	}
1084}
1085
1086static void
1087ahci_slotsfree(device_t dev)
1088{
1089	struct ahci_channel *ch = device_get_softc(dev);
1090	int i;
1091
1092	/* Free all dma slots */
1093	for (i = 0; i < ch->numslots; i++) {
1094		struct ahci_slot *slot = &ch->slot[i];
1095
1096		callout_drain(&slot->timeout);
1097		if (slot->dma.data_map) {
1098			bus_dmamap_destroy(ch->dma.data_tag, slot->dma.data_map);
1099			slot->dma.data_map = NULL;
1100		}
1101	}
1102}
1103
1104static void
1105ahci_phy_check_events(device_t dev, u_int32_t serr)
1106{
1107	struct ahci_channel *ch = device_get_softc(dev);
1108
1109	if ((serr & ATA_SE_PHY_CHANGED) && (ch->pm_level == 0)) {
1110		u_int32_t status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
1111		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
1112		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
1113		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE)) {
1114			if (bootverbose)
1115				device_printf(dev, "CONNECT requested\n");
1116			ahci_reset(dev);
1117		} else {
1118			if (bootverbose)
1119				device_printf(dev, "DISCONNECT requested\n");
1120			ch->devices = 0;
1121		}
1122	}
1123}
1124
1125static void
1126ahci_notify_events(device_t dev, u_int32_t status)
1127{
1128	struct ahci_channel *ch = device_get_softc(dev);
1129	struct cam_path *dpath;
1130	int i;
1131
1132	ATA_OUTL(ch->r_mem, AHCI_P_SNTF, status);
1133	if (bootverbose)
1134		device_printf(dev, "SNTF 0x%04x\n", status);
1135	for (i = 0; i < 16; i++) {
1136		if ((status & (1 << i)) == 0)
1137			continue;
1138		if (xpt_create_path(&dpath, NULL,
1139		    xpt_path_path_id(ch->path), i, 0) == CAM_REQ_CMP) {
1140			xpt_async(AC_SCSI_AEN, dpath, NULL);
1141			xpt_free_path(dpath);
1142		}
1143	}
1144}
1145
1146static void
1147ahci_ch_intr_locked(void *data)
1148{
1149	device_t dev = (device_t)data;
1150	struct ahci_channel *ch = device_get_softc(dev);
1151
1152	mtx_lock(&ch->mtx);
1153	ahci_ch_intr(data);
1154	mtx_unlock(&ch->mtx);
1155}
1156
1157static void
1158ahci_ch_pm(void *arg)
1159{
1160	device_t dev = (device_t)arg;
1161	struct ahci_channel *ch = device_get_softc(dev);
1162	uint32_t work;
1163
1164	if (ch->numrslots != 0)
1165		return;
1166	work = ATA_INL(ch->r_mem, AHCI_P_CMD);
1167	if (ch->pm_level == 4)
1168		work |= AHCI_P_CMD_PARTIAL;
1169	else
1170		work |= AHCI_P_CMD_SLUMBER;
1171	ATA_OUTL(ch->r_mem, AHCI_P_CMD, work);
1172}
1173
1174static void
1175ahci_ch_intr(void *data)
1176{
1177	device_t dev = (device_t)data;
1178	struct ahci_channel *ch = device_get_softc(dev);
1179	uint32_t istatus, sstatus, cstatus, serr = 0, sntf = 0, ok, err;
1180	enum ahci_err_type et;
1181	int i, ccs, ncq_err = 0;
1182
1183	/* Read and clear interrupt statuses. */
1184	istatus = ATA_INL(ch->r_mem, AHCI_P_IS);
1185	if (istatus == 0)
1186		return;
1187	ATA_OUTL(ch->r_mem, AHCI_P_IS, istatus);
1188	/* Read command statuses. */
1189	sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1190	cstatus = ATA_INL(ch->r_mem, AHCI_P_CI);
1191	if ((istatus & AHCI_P_IX_SDB) && (ch->caps & AHCI_CAP_SSNTF))
1192		sntf = ATA_INL(ch->r_mem, AHCI_P_SNTF);
1193	/* Process PHY events */
1194	if (istatus & (AHCI_P_IX_PC | AHCI_P_IX_PRC | AHCI_P_IX_OF |
1195	    AHCI_P_IX_IF | AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1196		serr = ATA_INL(ch->r_mem, AHCI_P_SERR);
1197		if (serr) {
1198			ATA_OUTL(ch->r_mem, AHCI_P_SERR, serr);
1199			ahci_phy_check_events(dev, serr);
1200		}
1201	}
1202	/* Process command errors */
1203	if (istatus & (AHCI_P_IX_OF | AHCI_P_IX_IF |
1204	    AHCI_P_IX_HBD | AHCI_P_IX_HBF | AHCI_P_IX_TFE)) {
1205//device_printf(dev, "%s ERROR is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1206//    __func__, istatus, cstatus, sstatus, ch->rslots, ATA_INL(ch->r_mem, AHCI_P_TFD),
1207//    serr);
1208		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1209		    >> AHCI_P_CMD_CCS_SHIFT;
1210		err = ch->rslots & (cstatus | sstatus);
1211		/* Kick controller into sane state */
1212		ahci_stop(dev);
1213		ahci_start(dev);
1214	} else {
1215		ccs = 0;
1216		err = 0;
1217	}
1218	/* Complete all successfull commands. */
1219	ok = ch->rslots & ~(cstatus | sstatus);
1220	for (i = 0; i < ch->numslots; i++) {
1221		if ((ok >> i) & 1)
1222			ahci_end_transaction(&ch->slot[i], AHCI_ERR_NONE);
1223	}
1224	/* On error, complete the rest of commands with error statuses. */
1225	if (err) {
1226		if (ch->frozen) {
1227			union ccb *fccb = ch->frozen;
1228			ch->frozen = NULL;
1229			fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1230			if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1231				xpt_freeze_devq(fccb->ccb_h.path, 1);
1232				fccb->ccb_h.status |= CAM_DEV_QFRZN;
1233			}
1234			xpt_done(fccb);
1235		}
1236		for (i = 0; i < ch->numslots; i++) {
1237			/* XXX: reqests in loading state. */
1238			if (((err >> i) & 1) == 0)
1239				continue;
1240			if (istatus & AHCI_P_IX_TFE) {
1241				/* Task File Error */
1242				if (ch->numtslots == 0) {
1243					/* Untagged operation. */
1244					if (i == ccs)
1245						et = AHCI_ERR_TFE;
1246					else
1247						et = AHCI_ERR_INNOCENT;
1248				} else {
1249					/* Tagged operation. */
1250					et = AHCI_ERR_NCQ;
1251					ncq_err = 1;
1252				}
1253			} else if (istatus & AHCI_P_IX_IF) {
1254				if (ch->numtslots == 0 && i != ccs)
1255					et = AHCI_ERR_INNOCENT;
1256				else
1257					et = AHCI_ERR_SATA;
1258			} else
1259				et = AHCI_ERR_INVALID;
1260			ahci_end_transaction(&ch->slot[i], et);
1261		}
1262		if (ncq_err)
1263			ahci_issue_read_log(dev);
1264	}
1265	/* Process NOTIFY events */
1266	if (sntf)
1267		ahci_notify_events(dev, sntf);
1268}
1269
1270/* Must be called with channel locked. */
1271static int
1272ahci_check_collision(device_t dev, union ccb *ccb)
1273{
1274	struct ahci_channel *ch = device_get_softc(dev);
1275
1276	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1277	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1278		/* Tagged command while untagged are active. */
1279		if (ch->numrslots != 0 && ch->numtslots == 0)
1280			return (1);
1281		/* Tagged command while tagged to other target is active. */
1282		if (ch->numtslots != 0 &&
1283		    ch->taggedtarget != ccb->ccb_h.target_id)
1284			return (1);
1285		/* Tagged command while we have no supported tag free. */
1286		if (((~ch->oslots) & (0xffffffff >> (32 -
1287		    ch->curr[ccb->ccb_h.target_id].tags))) == 0)
1288			return (1);
1289	} else {
1290		/* Untagged command while tagged are active. */
1291		if (ch->numrslots != 0 && ch->numtslots != 0)
1292			return (1);
1293	}
1294	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1295	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT))) {
1296		/* Atomic command while anything active. */
1297		if (ch->numrslots != 0)
1298			return (1);
1299	}
1300       /* We have some atomic command running. */
1301       if (ch->aslots != 0)
1302               return (1);
1303	return (0);
1304}
1305
1306/* Must be called with channel locked. */
1307static void
1308ahci_begin_transaction(device_t dev, union ccb *ccb)
1309{
1310	struct ahci_channel *ch = device_get_softc(dev);
1311	struct ahci_slot *slot;
1312	int tag, tags;
1313
1314	/* Choose empty slot. */
1315	tags = ch->numslots;
1316	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1317	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA))
1318		tags = ch->curr[ccb->ccb_h.target_id].tags;
1319	tag = ch->lastslot;
1320	while (1) {
1321		if (tag >= tags)
1322			tag = 0;
1323		if (ch->slot[tag].state == AHCI_SLOT_EMPTY)
1324			break;
1325		tag++;
1326	};
1327	ch->lastslot = tag;
1328	/* Occupy chosen slot. */
1329	slot = &ch->slot[tag];
1330	slot->ccb = ccb;
1331	/* Stop PM timer. */
1332	if (ch->numrslots == 0 && ch->pm_level > 3)
1333		callout_stop(&ch->pm_timer);
1334	/* Update channel stats. */
1335	ch->oslots |= (1 << slot->slot);
1336	ch->numrslots++;
1337	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1338	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1339		ch->numtslots++;
1340		ch->taggedtarget = ccb->ccb_h.target_id;
1341	}
1342	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1343	    (ccb->ataio.cmd.flags & (CAM_ATAIO_CONTROL | CAM_ATAIO_NEEDRESULT)))
1344		ch->aslots |= (1 << slot->slot);
1345	slot->dma.nsegs = 0;
1346	/* If request moves data, setup and load SG list */
1347	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1348		void *buf;
1349		bus_size_t size;
1350
1351		slot->state = AHCI_SLOT_LOADING;
1352		if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1353			buf = ccb->ataio.data_ptr;
1354			size = ccb->ataio.dxfer_len;
1355		} else {
1356			buf = ccb->csio.data_ptr;
1357			size = ccb->csio.dxfer_len;
1358		}
1359		bus_dmamap_load(ch->dma.data_tag, slot->dma.data_map,
1360		    buf, size, ahci_dmasetprd, slot, 0);
1361	} else
1362		ahci_execute_transaction(slot);
1363}
1364
1365/* Locked by busdma engine. */
1366static void
1367ahci_dmasetprd(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1368{
1369	struct ahci_slot *slot = arg;
1370	struct ahci_channel *ch = device_get_softc(slot->dev);
1371	struct ahci_cmd_tab *ctp;
1372	struct ahci_dma_prd *prd;
1373	int i;
1374
1375	if (error) {
1376		device_printf(slot->dev, "DMA load error\n");
1377		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1378		return;
1379	}
1380	KASSERT(nsegs <= AHCI_SG_ENTRIES, ("too many DMA segment entries\n"));
1381	/* Get a piece of the workspace for this request */
1382	ctp = (struct ahci_cmd_tab *)
1383		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1384	/* Fill S/G table */
1385	prd = &ctp->prd_tab[0];
1386	for (i = 0; i < nsegs; i++) {
1387		prd[i].dba = htole64(segs[i].ds_addr);
1388		prd[i].dbc = htole32((segs[i].ds_len - 1) & AHCI_PRD_MASK);
1389	}
1390	slot->dma.nsegs = nsegs;
1391	bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1392	    ((slot->ccb->ccb_h.flags & CAM_DIR_IN) ?
1393	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE));
1394	ahci_execute_transaction(slot);
1395}
1396
1397/* Must be called with channel locked. */
1398static void
1399ahci_execute_transaction(struct ahci_slot *slot)
1400{
1401	device_t dev = slot->dev;
1402	struct ahci_channel *ch = device_get_softc(dev);
1403	struct ahci_cmd_tab *ctp;
1404	struct ahci_cmd_list *clp;
1405	union ccb *ccb = slot->ccb;
1406	int port = ccb->ccb_h.target_id & 0x0f;
1407	int fis_size;
1408
1409	/* Get a piece of the workspace for this request */
1410	ctp = (struct ahci_cmd_tab *)
1411		(ch->dma.work + AHCI_CT_OFFSET + (AHCI_CT_SIZE * slot->slot));
1412	/* Setup the FIS for this request */
1413	if (!(fis_size = ahci_setup_fis(dev, ctp, ccb, slot->slot))) {
1414		device_printf(ch->dev, "Setting up SATA FIS failed\n");
1415		ahci_end_transaction(slot, AHCI_ERR_INVALID);
1416		return;
1417	}
1418	/* Setup the command list entry */
1419	clp = (struct ahci_cmd_list *)
1420	    (ch->dma.work + AHCI_CL_OFFSET + (AHCI_CL_SIZE * slot->slot));
1421	clp->prd_length = slot->dma.nsegs;
1422	clp->cmd_flags = (ccb->ccb_h.flags & CAM_DIR_OUT ? AHCI_CMD_WRITE : 0) |
1423		     (ccb->ccb_h.func_code == XPT_SCSI_IO ?
1424		      (AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH) : 0) |
1425		     (fis_size / sizeof(u_int32_t)) |
1426		     (port << 12);
1427	/* Special handling for Soft Reset command. */
1428	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1429	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1430	    (ccb->ataio.cmd.control & ATA_A_RESET)) {
1431		/* Kick controller into sane state */
1432		ahci_stop(dev);
1433		ahci_clo(dev);
1434		ahci_start(dev);
1435		clp->cmd_flags |= AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY;
1436	}
1437	clp->bytecount = 0;
1438	clp->cmd_table_phys = htole64(ch->dma.work_bus + AHCI_CT_OFFSET +
1439				  (AHCI_CT_SIZE * slot->slot));
1440	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1441	    BUS_DMASYNC_PREWRITE);
1442	bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1443	    BUS_DMASYNC_PREREAD);
1444	/* Set ACTIVE bit for NCQ commands. */
1445	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1446	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1447		ATA_OUTL(ch->r_mem, AHCI_P_SACT, 1 << slot->slot);
1448	}
1449	/* Issue command to the controller. */
1450	slot->state = AHCI_SLOT_RUNNING;
1451	ch->rslots |= (1 << slot->slot);
1452	ATA_OUTL(ch->r_mem, AHCI_P_CI, (1 << slot->slot));
1453	/* Device reset commands doesn't interrupt. Poll them. */
1454	if (ccb->ccb_h.func_code == XPT_ATA_IO &&
1455	    (ccb->ataio.cmd.command == ATA_DEVICE_RESET ||
1456	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))) {
1457		int count, timeout = ccb->ccb_h.timeout;
1458		enum ahci_err_type et = AHCI_ERR_NONE;
1459
1460		for (count = 0; count < timeout; count++) {
1461			DELAY(1000);
1462			if (!(ATA_INL(ch->r_mem, AHCI_P_CI) & (1 << slot->slot)))
1463				break;
1464			if (ATA_INL(ch->r_mem, AHCI_P_TFD) & ATA_S_ERROR) {
1465				device_printf(ch->dev,
1466				    "Poll error on slot %d, TFD: %04x\n",
1467				    slot->slot, ATA_INL(ch->r_mem, AHCI_P_TFD));
1468				et = AHCI_ERR_TFE;
1469				break;
1470			}
1471			/* Workaround for ATI SB600/SB700 chipsets. */
1472			if (ccb->ccb_h.target_id == 15 &&
1473			    pci_get_vendor(device_get_parent(dev)) == 0x1002 &&
1474			    (ATA_INL(ch->r_mem, AHCI_P_IS) & AHCI_P_IX_IPM)) {
1475				et = AHCI_ERR_TIMEOUT;
1476				break;
1477			}
1478		}
1479		if (timeout && (count >= timeout)) {
1480			device_printf(ch->dev,
1481			    "Poll timeout on slot %d\n", slot->slot);
1482			et = AHCI_ERR_TIMEOUT;
1483		}
1484		if (et != AHCI_ERR_NONE) {
1485			/* Kick controller into sane state */
1486			ahci_stop(ch->dev);
1487			ahci_start(ch->dev);
1488		}
1489		ahci_end_transaction(slot, et);
1490		return;
1491	}
1492	/* Start command execution timeout */
1493	callout_reset(&slot->timeout, (int)ccb->ccb_h.timeout * hz / 2000,
1494	    (timeout_t*)ahci_timeout, slot);
1495	return;
1496}
1497
1498/* Locked by callout mechanism. */
1499static void
1500ahci_timeout(struct ahci_slot *slot)
1501{
1502	device_t dev = slot->dev;
1503	struct ahci_channel *ch = device_get_softc(dev);
1504	uint32_t sstatus;
1505	int ccs;
1506	int i;
1507
1508	/* Check for stale timeout. */
1509	if (slot->state < AHCI_SLOT_RUNNING)
1510		return;
1511
1512	/* Check if slot was not being executed last time we checked. */
1513	if (slot->state < AHCI_SLOT_EXECUTING) {
1514		/* Check if slot started executing. */
1515		sstatus = ATA_INL(ch->r_mem, AHCI_P_SACT);
1516		ccs = (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CCS_MASK)
1517		    >> AHCI_P_CMD_CCS_SHIFT;
1518		if ((sstatus & (1 << slot->slot)) != 0 || ccs == slot->slot)
1519			slot->state = AHCI_SLOT_EXECUTING;
1520
1521		callout_reset(&slot->timeout,
1522		    (int)slot->ccb->ccb_h.timeout * hz / 2000,
1523		    (timeout_t*)ahci_timeout, slot);
1524		return;
1525	}
1526
1527	device_printf(dev, "Timeout on slot %d\n", slot->slot);
1528	device_printf(dev, "is %08x cs %08x ss %08x rs %08x tfd %02x serr %08x\n",
1529	    ATA_INL(ch->r_mem, AHCI_P_IS), ATA_INL(ch->r_mem, AHCI_P_CI),
1530	    ATA_INL(ch->r_mem, AHCI_P_SACT), ch->rslots,
1531	    ATA_INL(ch->r_mem, AHCI_P_TFD), ATA_INL(ch->r_mem, AHCI_P_SERR));
1532
1533	ch->fatalerr = 1;
1534	/* Handle frozen command. */
1535	if (ch->frozen) {
1536		union ccb *fccb = ch->frozen;
1537		ch->frozen = NULL;
1538		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1539		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1540			xpt_freeze_devq(fccb->ccb_h.path, 1);
1541			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1542		}
1543		xpt_done(fccb);
1544	}
1545	/* Handle command with timeout. */
1546	ahci_end_transaction(&ch->slot[slot->slot], AHCI_ERR_TIMEOUT);
1547	/* Handle the rest of commands. */
1548	for (i = 0; i < ch->numslots; i++) {
1549		/* Do we have a running request on slot? */
1550		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1551			continue;
1552		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1553	}
1554}
1555
1556/* Must be called with channel locked. */
1557static void
1558ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
1559{
1560	device_t dev = slot->dev;
1561	struct ahci_channel *ch = device_get_softc(dev);
1562	union ccb *ccb = slot->ccb;
1563
1564	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
1565	    BUS_DMASYNC_POSTWRITE);
1566	/* Read result registers to the result struct
1567	 * May be incorrect if several commands finished same time,
1568	 * so read only when sure or have to.
1569	 */
1570	if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1571		struct ata_res *res = &ccb->ataio.res;
1572
1573		if ((et == AHCI_ERR_TFE) ||
1574		    (ccb->ataio.cmd.flags & CAM_ATAIO_NEEDRESULT)) {
1575			u_int8_t *fis = ch->dma.rfis + 0x40;
1576			uint16_t tfd = ATA_INL(ch->r_mem, AHCI_P_TFD);
1577
1578			bus_dmamap_sync(ch->dma.rfis_tag, ch->dma.rfis_map,
1579			    BUS_DMASYNC_POSTREAD);
1580			res->status = tfd;
1581			res->error = tfd >> 8;
1582			res->lba_low = fis[4];
1583			res->lba_mid = fis[5];
1584			res->lba_high = fis[6];
1585			res->device = fis[7];
1586			res->lba_low_exp = fis[8];
1587			res->lba_mid_exp = fis[9];
1588			res->lba_high_exp = fis[10];
1589			res->sector_count = fis[12];
1590			res->sector_count_exp = fis[13];
1591		} else
1592			bzero(res, sizeof(*res));
1593	}
1594	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1595		bus_dmamap_sync(ch->dma.data_tag, slot->dma.data_map,
1596		    (ccb->ccb_h.flags & CAM_DIR_IN) ?
1597		    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
1598		bus_dmamap_unload(ch->dma.data_tag, slot->dma.data_map);
1599	}
1600	/* In case of error, freeze device for proper recovery. */
1601	if ((et != AHCI_ERR_NONE) && (!ch->readlog) &&
1602	    !(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
1603		xpt_freeze_devq(ccb->ccb_h.path, 1);
1604		ccb->ccb_h.status |= CAM_DEV_QFRZN;
1605	}
1606	/* Set proper result status. */
1607	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1608	switch (et) {
1609	case AHCI_ERR_NONE:
1610		ccb->ccb_h.status |= CAM_REQ_CMP;
1611		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1612			ccb->csio.scsi_status = SCSI_STATUS_OK;
1613		break;
1614	case AHCI_ERR_INVALID:
1615		ch->fatalerr = 1;
1616		ccb->ccb_h.status |= CAM_REQ_INVALID;
1617		break;
1618	case AHCI_ERR_INNOCENT:
1619		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1620		break;
1621	case AHCI_ERR_TFE:
1622	case AHCI_ERR_NCQ:
1623		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1624			ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1625			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
1626		} else {
1627			ccb->ccb_h.status |= CAM_ATA_STATUS_ERROR;
1628		}
1629		break;
1630	case AHCI_ERR_SATA:
1631		ch->fatalerr = 1;
1632		if (!ch->readlog) {
1633			xpt_freeze_simq(ch->sim, 1);
1634			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1635			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1636		}
1637		ccb->ccb_h.status |= CAM_UNCOR_PARITY;
1638		break;
1639	case AHCI_ERR_TIMEOUT:
1640		/* Do no treat soft-reset timeout as fatal here. */
1641		if (ccb->ccb_h.func_code != XPT_ATA_IO ||
1642	            !(ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL))
1643			ch->fatalerr = 1;
1644		if (!ch->readlog) {
1645			xpt_freeze_simq(ch->sim, 1);
1646			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
1647			ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1648		}
1649		ccb->ccb_h.status |= CAM_CMD_TIMEOUT;
1650		break;
1651	default:
1652		ch->fatalerr = 1;
1653		ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
1654	}
1655	/* Free slot. */
1656	ch->oslots &= ~(1 << slot->slot);
1657	ch->rslots &= ~(1 << slot->slot);
1658	ch->aslots &= ~(1 << slot->slot);
1659	slot->state = AHCI_SLOT_EMPTY;
1660	slot->ccb = NULL;
1661	/* Update channel stats. */
1662	ch->numrslots--;
1663	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1664	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
1665		ch->numtslots--;
1666	}
1667	/* If it was first request of reset sequence and there is no error,
1668	 * proceed to second request. */
1669	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
1670	    (ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) &&
1671	    (ccb->ataio.cmd.control & ATA_A_RESET) &&
1672	    et == AHCI_ERR_NONE) {
1673		ccb->ataio.cmd.control &= ~ATA_A_RESET;
1674		ahci_begin_transaction(dev, ccb);
1675		return;
1676	}
1677	/* If it was our READ LOG command - process it. */
1678	if (ch->readlog) {
1679		ahci_process_read_log(dev, ccb);
1680	/* If it was NCQ command error, put result on hold. */
1681	} else if (et == AHCI_ERR_NCQ) {
1682		ch->hold[slot->slot] = ccb;
1683	} else
1684		xpt_done(ccb);
1685	/* Unfreeze frozen command. */
1686	if (ch->frozen && !ahci_check_collision(dev, ch->frozen)) {
1687		union ccb *fccb = ch->frozen;
1688		ch->frozen = NULL;
1689		ahci_begin_transaction(dev, fccb);
1690		xpt_release_simq(ch->sim, TRUE);
1691	}
1692	/* If we have no other active commands, ... */
1693	if (ch->rslots == 0) {
1694		/* if there was fatal error - reset port. */
1695		if (ch->fatalerr) {
1696			ahci_reset(dev);
1697		}
1698	}
1699	/* Start PM timer. */
1700	if (ch->numrslots == 0 && ch->pm_level > 3) {
1701		callout_schedule(&ch->pm_timer,
1702		    (ch->pm_level == 4) ? hz / 1000 : hz / 8);
1703	}
1704}
1705
1706static void
1707ahci_issue_read_log(device_t dev)
1708{
1709	struct ahci_channel *ch = device_get_softc(dev);
1710	union ccb *ccb;
1711	struct ccb_ataio *ataio;
1712	int i;
1713
1714	ch->readlog = 1;
1715	/* Find some holden command. */
1716	for (i = 0; i < ch->numslots; i++) {
1717		if (ch->hold[i])
1718			break;
1719	}
1720	ccb = xpt_alloc_ccb_nowait();
1721	if (ccb == NULL) {
1722		device_printf(dev, "Unable allocate READ LOG command");
1723		return; /* XXX */
1724	}
1725	ccb->ccb_h = ch->hold[i]->ccb_h;	/* Reuse old header. */
1726	ccb->ccb_h.func_code = XPT_ATA_IO;
1727	ccb->ccb_h.flags = CAM_DIR_IN;
1728	ccb->ccb_h.timeout = 1000;	/* 1s should be enough. */
1729	ataio = &ccb->ataio;
1730	ataio->data_ptr = malloc(512, M_AHCI, M_NOWAIT);
1731	if (ataio->data_ptr == NULL) {
1732		device_printf(dev, "Unable allocate memory for READ LOG command");
1733		return; /* XXX */
1734	}
1735	ataio->dxfer_len = 512;
1736	bzero(&ataio->cmd, sizeof(ataio->cmd));
1737	ataio->cmd.flags = CAM_ATAIO_48BIT;
1738	ataio->cmd.command = 0x2F;	/* READ LOG EXT */
1739	ataio->cmd.sector_count = 1;
1740	ataio->cmd.sector_count_exp = 0;
1741	ataio->cmd.lba_low = 0x10;
1742	ataio->cmd.lba_mid = 0;
1743	ataio->cmd.lba_mid_exp = 0;
1744	/* Freeze SIM while doing READ LOG EXT. */
1745	xpt_freeze_simq(ch->sim, 1);
1746	ahci_begin_transaction(dev, ccb);
1747}
1748
1749static void
1750ahci_process_read_log(device_t dev, union ccb *ccb)
1751{
1752	struct ahci_channel *ch = device_get_softc(dev);
1753	uint8_t *data;
1754	struct ata_res *res;
1755	int i;
1756
1757	ch->readlog = 0;
1758
1759	data = ccb->ataio.data_ptr;
1760	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1761	    (data[0] & 0x80) == 0) {
1762		for (i = 0; i < ch->numslots; i++) {
1763			if (!ch->hold[i])
1764				continue;
1765			if ((data[0] & 0x1F) == i) {
1766				res = &ch->hold[i]->ataio.res;
1767				res->status = data[2];
1768				res->error = data[3];
1769				res->lba_low = data[4];
1770				res->lba_mid = data[5];
1771				res->lba_high = data[6];
1772				res->device = data[7];
1773				res->lba_low_exp = data[8];
1774				res->lba_mid_exp = data[9];
1775				res->lba_high_exp = data[10];
1776				res->sector_count = data[12];
1777				res->sector_count_exp = data[13];
1778			} else {
1779				ch->hold[i]->ccb_h.status &= ~CAM_STATUS_MASK;
1780				ch->hold[i]->ccb_h.status |= CAM_REQUEUE_REQ;
1781			}
1782			xpt_done(ch->hold[i]);
1783			ch->hold[i] = NULL;
1784		}
1785	} else {
1786		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
1787			device_printf(dev, "Error while READ LOG EXT\n");
1788		else if ((data[0] & 0x80) == 0) {
1789			device_printf(dev, "Non-queued command error in READ LOG EXT\n");
1790		}
1791		for (i = 0; i < ch->numslots; i++) {
1792			if (!ch->hold[i])
1793				continue;
1794			xpt_done(ch->hold[i]);
1795			ch->hold[i] = NULL;
1796		}
1797	}
1798	free(ccb->ataio.data_ptr, M_AHCI);
1799	xpt_free_ccb(ccb);
1800	xpt_release_simq(ch->sim, TRUE);
1801}
1802
1803static void
1804ahci_start(device_t dev)
1805{
1806	struct ahci_channel *ch = device_get_softc(dev);
1807	u_int32_t cmd;
1808
1809	/* Clear SATA error register */
1810	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xFFFFFFFF);
1811	/* Clear any interrupts pending on this channel */
1812	ATA_OUTL(ch->r_mem, AHCI_P_IS, 0xFFFFFFFF);
1813	/* Start operations on this channel */
1814	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1815	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_ST |
1816	    (ch->pm_present ? AHCI_P_CMD_PMA : 0));
1817}
1818
1819static void
1820ahci_stop(device_t dev)
1821{
1822	struct ahci_channel *ch = device_get_softc(dev);
1823	u_int32_t cmd;
1824	int timeout;
1825
1826	/* Kill all activity on this channel */
1827	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1828	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_ST);
1829	/* Wait for activity stop. */
1830	timeout = 0;
1831	do {
1832		DELAY(1000);
1833		if (timeout++ > 1000) {
1834			device_printf(dev, "stopping AHCI engine failed\n");
1835			break;
1836		}
1837	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CR);
1838}
1839
1840static void
1841ahci_clo(device_t dev)
1842{
1843	struct ahci_channel *ch = device_get_softc(dev);
1844	u_int32_t cmd;
1845	int timeout;
1846
1847	/* Issue Command List Override if supported */
1848	if (ch->caps & AHCI_CAP_SCLO) {
1849		cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1850		cmd |= AHCI_P_CMD_CLO;
1851		ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd);
1852		timeout = 0;
1853		do {
1854			DELAY(1000);
1855			if (timeout++ > 1000) {
1856			    device_printf(dev, "executing CLO failed\n");
1857			    break;
1858			}
1859		} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_CLO);
1860	}
1861}
1862
1863static void
1864ahci_stop_fr(device_t dev)
1865{
1866	struct ahci_channel *ch = device_get_softc(dev);
1867	u_int32_t cmd;
1868	int timeout;
1869
1870	/* Kill all FIS reception on this channel */
1871	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1872	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd & ~AHCI_P_CMD_FRE);
1873	/* Wait for FIS reception stop. */
1874	timeout = 0;
1875	do {
1876		DELAY(1000);
1877		if (timeout++ > 1000) {
1878			device_printf(dev, "stopping AHCI FR engine failed\n");
1879			break;
1880		}
1881	} while (ATA_INL(ch->r_mem, AHCI_P_CMD) & AHCI_P_CMD_FR);
1882}
1883
1884static void
1885ahci_start_fr(device_t dev)
1886{
1887	struct ahci_channel *ch = device_get_softc(dev);
1888	u_int32_t cmd;
1889
1890	/* Start FIS reception on this channel */
1891	cmd = ATA_INL(ch->r_mem, AHCI_P_CMD);
1892	ATA_OUTL(ch->r_mem, AHCI_P_CMD, cmd | AHCI_P_CMD_FRE);
1893}
1894
1895static int
1896ahci_wait_ready(device_t dev, int t)
1897{
1898	struct ahci_channel *ch = device_get_softc(dev);
1899	int timeout = 0;
1900	uint32_t val;
1901
1902	while ((val = ATA_INL(ch->r_mem, AHCI_P_TFD)) &
1903	    (ATA_S_BUSY | ATA_S_DRQ)) {
1904		DELAY(1000);
1905		if (timeout++ > t) {
1906			device_printf(dev, "port is not ready (timeout %dms) "
1907			    "tfd = %08x\n", t, val);
1908			return (EBUSY);
1909		}
1910	}
1911	if (bootverbose)
1912		device_printf(dev, "ready wait time=%dms\n", timeout);
1913	return (0);
1914}
1915
1916static void
1917ahci_reset(device_t dev)
1918{
1919	struct ahci_channel *ch = device_get_softc(dev);
1920	struct ahci_controller *ctlr = device_get_softc(device_get_parent(dev));
1921	int i;
1922
1923	if (bootverbose)
1924		device_printf(dev, "AHCI reset...\n");
1925	/* Requeue freezed command. */
1926	if (ch->frozen) {
1927		union ccb *fccb = ch->frozen;
1928		ch->frozen = NULL;
1929		fccb->ccb_h.status = CAM_REQUEUE_REQ | CAM_RELEASE_SIMQ;
1930		if (!(fccb->ccb_h.status & CAM_DEV_QFRZN)) {
1931			xpt_freeze_devq(fccb->ccb_h.path, 1);
1932			fccb->ccb_h.status |= CAM_DEV_QFRZN;
1933		}
1934		xpt_done(fccb);
1935	}
1936	/* Kill the engine and requeue all running commands. */
1937	ahci_stop(dev);
1938	for (i = 0; i < ch->numslots; i++) {
1939		/* Do we have a running request on slot? */
1940		if (ch->slot[i].state < AHCI_SLOT_RUNNING)
1941			continue;
1942		/* XXX; Commands in loading state. */
1943		ahci_end_transaction(&ch->slot[i], AHCI_ERR_INNOCENT);
1944	}
1945	for (i = 0; i < ch->numslots; i++) {
1946		if (!ch->hold[i])
1947			continue;
1948		xpt_done(ch->hold[i]);
1949		ch->hold[i] = NULL;
1950	}
1951	ch->fatalerr = 0;
1952	/* Tell the XPT about the event */
1953	xpt_async(AC_BUS_RESET, ch->path, NULL);
1954	/* Disable port interrupts */
1955	ATA_OUTL(ch->r_mem, AHCI_P_IE, 0);
1956	/* Reset and reconnect PHY, */
1957	if (!ahci_sata_phy_reset(dev, 0)) {
1958		if (bootverbose)
1959			device_printf(dev,
1960			    "AHCI reset done: phy reset found no device\n");
1961		ch->devices = 0;
1962		/* Enable wanted port interrupts */
1963		ATA_OUTL(ch->r_mem, AHCI_P_IE,
1964		    (AHCI_P_IX_CPD | AHCI_P_IX_PRC | AHCI_P_IX_PC));
1965		return;
1966	}
1967	/* Wait for clearing busy status. */
1968	if (ahci_wait_ready(dev, 10000)) {
1969		device_printf(dev, "device ready timeout\n");
1970		ahci_clo(dev);
1971	}
1972	ahci_start(dev);
1973	ch->devices = 1;
1974	/* Enable wanted port interrupts */
1975	ATA_OUTL(ch->r_mem, AHCI_P_IE,
1976	     (AHCI_P_IX_CPD | AHCI_P_IX_TFE | AHCI_P_IX_HBF |
1977	      AHCI_P_IX_HBD | AHCI_P_IX_IF | AHCI_P_IX_OF |
1978	      ((ch->pm_level == 0) ? AHCI_P_IX_PRC | AHCI_P_IX_PC : 0) |
1979	      AHCI_P_IX_DP | AHCI_P_IX_UF | (ctlr->ccc ? 0 : AHCI_P_IX_SDB) |
1980	      AHCI_P_IX_DS | AHCI_P_IX_PS | (ctlr->ccc ? 0 : AHCI_P_IX_DHR)));
1981	if (bootverbose)
1982		device_printf(dev, "AHCI reset done: device found\n");
1983}
1984
1985static int
1986ahci_setup_fis(device_t dev, struct ahci_cmd_tab *ctp, union ccb *ccb, int tag)
1987{
1988	struct ahci_channel *ch = device_get_softc(dev);
1989	u_int8_t *fis = &ctp->cfis[0];
1990
1991	bzero(ctp->cfis, 64);
1992	fis[0] = 0x27;  		/* host to device */
1993	fis[1] = (ccb->ccb_h.target_id & 0x0f);
1994	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1995		fis[1] |= 0x80;
1996		fis[2] = ATA_PACKET_CMD;
1997		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE &&
1998		    ch->curr[ccb->ccb_h.target_id].mode >= ATA_DMA)
1999			fis[3] = ATA_F_DMA;
2000		else {
2001			fis[5] = ccb->csio.dxfer_len;
2002		        fis[6] = ccb->csio.dxfer_len >> 8;
2003		}
2004		fis[7] = ATA_D_LBA;
2005		fis[15] = ATA_A_4BIT;
2006		bzero(ctp->acmd, 32);
2007		bcopy((ccb->ccb_h.flags & CAM_CDB_POINTER) ?
2008		    ccb->csio.cdb_io.cdb_ptr : ccb->csio.cdb_io.cdb_bytes,
2009		    ctp->acmd, ccb->csio.cdb_len);
2010	} else if ((ccb->ataio.cmd.flags & CAM_ATAIO_CONTROL) == 0) {
2011		fis[1] |= 0x80;
2012		fis[2] = ccb->ataio.cmd.command;
2013		fis[3] = ccb->ataio.cmd.features;
2014		fis[4] = ccb->ataio.cmd.lba_low;
2015		fis[5] = ccb->ataio.cmd.lba_mid;
2016		fis[6] = ccb->ataio.cmd.lba_high;
2017		fis[7] = ccb->ataio.cmd.device;
2018		fis[8] = ccb->ataio.cmd.lba_low_exp;
2019		fis[9] = ccb->ataio.cmd.lba_mid_exp;
2020		fis[10] = ccb->ataio.cmd.lba_high_exp;
2021		fis[11] = ccb->ataio.cmd.features_exp;
2022		if (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA) {
2023			fis[12] = tag << 3;
2024			fis[13] = 0;
2025		} else {
2026			fis[12] = ccb->ataio.cmd.sector_count;
2027			fis[13] = ccb->ataio.cmd.sector_count_exp;
2028		}
2029		fis[15] = ATA_A_4BIT;
2030	} else {
2031		fis[15] = ccb->ataio.cmd.control;
2032	}
2033	return (20);
2034}
2035
2036static int
2037ahci_sata_connect(struct ahci_channel *ch)
2038{
2039	u_int32_t status;
2040	int timeout;
2041
2042	/* Wait up to 100ms for "connect well" */
2043	for (timeout = 0; timeout < 100 ; timeout++) {
2044		status = ATA_INL(ch->r_mem, AHCI_P_SSTS);
2045		if (((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_ONLINE) &&
2046		    ((status & ATA_SS_SPD_MASK) != ATA_SS_SPD_NO_SPEED) &&
2047		    ((status & ATA_SS_IPM_MASK) == ATA_SS_IPM_ACTIVE))
2048			break;
2049		if ((status & ATA_SS_DET_MASK) == ATA_SS_DET_PHY_OFFLINE) {
2050			if (bootverbose) {
2051				device_printf(ch->dev, "SATA offline status=%08x\n",
2052				    status);
2053			}
2054			return (0);
2055		}
2056		DELAY(1000);
2057	}
2058	if (timeout >= 100) {
2059		if (bootverbose) {
2060			device_printf(ch->dev, "SATA connect timeout status=%08x\n",
2061			    status);
2062		}
2063		return (0);
2064	}
2065	if (bootverbose) {
2066		device_printf(ch->dev, "SATA connect time=%dms status=%08x\n",
2067		    timeout, status);
2068	}
2069	/* Clear SATA error register */
2070	ATA_OUTL(ch->r_mem, AHCI_P_SERR, 0xffffffff);
2071	return (1);
2072}
2073
2074static int
2075ahci_sata_phy_reset(device_t dev, int quick)
2076{
2077	struct ahci_channel *ch = device_get_softc(dev);
2078	int sata_rev;
2079	uint32_t val;
2080
2081	if (quick) {
2082		val = ATA_INL(ch->r_mem, AHCI_P_SCTL);
2083		if ((val & ATA_SC_DET_MASK) == ATA_SC_DET_IDLE)
2084			return (ahci_sata_connect(ch));
2085	}
2086
2087	if (bootverbose)
2088		device_printf(dev, "hardware reset ...\n");
2089	sata_rev = ch->user[ch->pm_present ? 15 : 0].revision;
2090	if (sata_rev == 1)
2091		val = ATA_SC_SPD_SPEED_GEN1;
2092	else if (sata_rev == 2)
2093		val = ATA_SC_SPD_SPEED_GEN2;
2094	else if (sata_rev == 3)
2095		val = ATA_SC_SPD_SPEED_GEN3;
2096	else
2097		val = 0;
2098	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2099	    ATA_SC_DET_RESET | val |
2100	    ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER);
2101	DELAY(5000);
2102	ATA_OUTL(ch->r_mem, AHCI_P_SCTL,
2103	    ATA_SC_DET_IDLE | val | ((ch->pm_level > 0) ? 0 :
2104	    (ATA_SC_IPM_DIS_PARTIAL | ATA_SC_IPM_DIS_SLUMBER)));
2105	DELAY(5000);
2106	return (ahci_sata_connect(ch));
2107}
2108
2109static void
2110ahciaction(struct cam_sim *sim, union ccb *ccb)
2111{
2112	device_t dev;
2113	struct ahci_channel *ch;
2114
2115	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahciaction func_code=%x\n",
2116	    ccb->ccb_h.func_code));
2117
2118	ch = (struct ahci_channel *)cam_sim_softc(sim);
2119	dev = ch->dev;
2120	switch (ccb->ccb_h.func_code) {
2121	/* Common cases first */
2122	case XPT_ATA_IO:	/* Execute the requested I/O operation */
2123	case XPT_SCSI_IO:
2124		if (ch->devices == 0) {
2125			ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2126			xpt_done(ccb);
2127			break;
2128		}
2129		/* Check for command collision. */
2130		if (ahci_check_collision(dev, ccb)) {
2131			/* Freeze command. */
2132			ch->frozen = ccb;
2133			/* We have only one frozen slot, so freeze simq also. */
2134			xpt_freeze_simq(ch->sim, 1);
2135			return;
2136		}
2137		ahci_begin_transaction(dev, ccb);
2138		break;
2139	case XPT_EN_LUN:		/* Enable LUN as a target */
2140	case XPT_TARGET_IO:		/* Execute target I/O request */
2141	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
2142	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
2143	case XPT_ABORT:			/* Abort the specified CCB */
2144		/* XXX Implement */
2145		ccb->ccb_h.status = CAM_REQ_INVALID;
2146		xpt_done(ccb);
2147		break;
2148	case XPT_SET_TRAN_SETTINGS:
2149	{
2150		struct	ccb_trans_settings *cts = &ccb->cts;
2151		struct	ahci_device *d;
2152
2153		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2154			d = &ch->curr[ccb->ccb_h.target_id];
2155		else
2156			d = &ch->user[ccb->ccb_h.target_id];
2157		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_REVISION)
2158			d->revision = cts->xport_specific.sata.revision;
2159		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_MODE)
2160			d->mode = cts->xport_specific.sata.mode;
2161		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_BYTECOUNT)
2162			d->bytecount = min(8192, cts->xport_specific.sata.bytecount);
2163		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_TAGS)
2164			d->tags = min(ch->numslots, cts->xport_specific.sata.tags);
2165		if (cts->xport_specific.sata.valid & CTS_SATA_VALID_PM)
2166			ch->pm_present = cts->xport_specific.sata.pm_present;
2167		ccb->ccb_h.status = CAM_REQ_CMP;
2168		xpt_done(ccb);
2169		break;
2170	}
2171	case XPT_GET_TRAN_SETTINGS:
2172	/* Get default/user set transfer settings for the target */
2173	{
2174		struct	ccb_trans_settings *cts = &ccb->cts;
2175		struct  ahci_device *d;
2176		uint32_t status;
2177
2178		if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
2179			d = &ch->curr[ccb->ccb_h.target_id];
2180		else
2181			d = &ch->user[ccb->ccb_h.target_id];
2182		cts->protocol = PROTO_ATA;
2183		cts->protocol_version = PROTO_VERSION_UNSPECIFIED;
2184		cts->transport = XPORT_SATA;
2185		cts->transport_version = XPORT_VERSION_UNSPECIFIED;
2186		cts->proto_specific.valid = 0;
2187		cts->xport_specific.sata.valid = 0;
2188		if (cts->type == CTS_TYPE_CURRENT_SETTINGS &&
2189		    (ccb->ccb_h.target_id == 15 ||
2190		    (ccb->ccb_h.target_id == 0 && !ch->pm_present))) {
2191			status = ATA_INL(ch->r_mem, AHCI_P_SSTS) & ATA_SS_SPD_MASK;
2192			if (status & 0x0f0) {
2193				cts->xport_specific.sata.revision =
2194				    (status & 0x0f0) >> 4;
2195				cts->xport_specific.sata.valid |=
2196				    CTS_SATA_VALID_REVISION;
2197			}
2198		} else {
2199			cts->xport_specific.sata.revision = d->revision;
2200			cts->xport_specific.sata.valid |= CTS_SATA_VALID_REVISION;
2201		}
2202		cts->xport_specific.sata.mode = d->mode;
2203		cts->xport_specific.sata.valid |= CTS_SATA_VALID_MODE;
2204		cts->xport_specific.sata.bytecount = d->bytecount;
2205		cts->xport_specific.sata.valid |= CTS_SATA_VALID_BYTECOUNT;
2206		cts->xport_specific.sata.pm_present = ch->pm_present;
2207		cts->xport_specific.sata.valid |= CTS_SATA_VALID_PM;
2208		cts->xport_specific.sata.tags = d->tags;
2209		cts->xport_specific.sata.valid |= CTS_SATA_VALID_TAGS;
2210		ccb->ccb_h.status = CAM_REQ_CMP;
2211		xpt_done(ccb);
2212		break;
2213	}
2214#if 0
2215	case XPT_CALC_GEOMETRY:
2216	{
2217		struct	  ccb_calc_geometry *ccg;
2218		uint32_t size_mb;
2219		uint32_t secs_per_cylinder;
2220
2221		ccg = &ccb->ccg;
2222		size_mb = ccg->volume_size
2223			/ ((1024L * 1024L) / ccg->block_size);
2224		if (size_mb >= 1024 && (aha->extended_trans != 0)) {
2225			if (size_mb >= 2048) {
2226				ccg->heads = 255;
2227				ccg->secs_per_track = 63;
2228			} else {
2229				ccg->heads = 128;
2230				ccg->secs_per_track = 32;
2231			}
2232		} else {
2233			ccg->heads = 64;
2234			ccg->secs_per_track = 32;
2235		}
2236		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2237		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2238		ccb->ccb_h.status = CAM_REQ_CMP;
2239		xpt_done(ccb);
2240		break;
2241	}
2242#endif
2243	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
2244	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
2245		ahci_reset(dev);
2246		ccb->ccb_h.status = CAM_REQ_CMP;
2247		xpt_done(ccb);
2248		break;
2249	case XPT_TERM_IO:		/* Terminate the I/O process */
2250		/* XXX Implement */
2251		ccb->ccb_h.status = CAM_REQ_INVALID;
2252		xpt_done(ccb);
2253		break;
2254	case XPT_PATH_INQ:		/* Path routing inquiry */
2255	{
2256		struct ccb_pathinq *cpi = &ccb->cpi;
2257
2258		cpi->version_num = 1; /* XXX??? */
2259		cpi->hba_inquiry = PI_SDTR_ABLE;
2260		if (ch->caps & AHCI_CAP_SNCQ)
2261			cpi->hba_inquiry |= PI_TAG_ABLE;
2262		if (ch->caps & AHCI_CAP_SPM)
2263			cpi->hba_inquiry |= PI_SATAPM;
2264		cpi->target_sprt = 0;
2265		cpi->hba_misc = PIM_SEQSCAN;
2266		cpi->hba_eng_cnt = 0;
2267		if (ch->caps & AHCI_CAP_SPM)
2268			cpi->max_target = 15;
2269		else
2270			cpi->max_target = 0;
2271		cpi->max_lun = 0;
2272		cpi->initiator_id = 0;
2273		cpi->bus_id = cam_sim_bus(sim);
2274		cpi->base_transfer_speed = 150000;
2275		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2276		strncpy(cpi->hba_vid, "AHCI", HBA_IDLEN);
2277		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2278		cpi->unit_number = cam_sim_unit(sim);
2279		cpi->transport = XPORT_SATA;
2280		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
2281		cpi->protocol = PROTO_ATA;
2282		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
2283		cpi->maxio = MAXPHYS;
2284		/* ATI SB600 can't handle 256 sectors with FPDMA (NCQ). */
2285		if (pci_get_devid(device_get_parent(dev)) == 0x43801002)
2286			cpi->maxio = min(cpi->maxio, 128 * 512);
2287		cpi->ccb_h.status = CAM_REQ_CMP;
2288		xpt_done(ccb);
2289		break;
2290	}
2291	default:
2292		ccb->ccb_h.status = CAM_REQ_INVALID;
2293		xpt_done(ccb);
2294		break;
2295	}
2296}
2297
2298static void
2299ahcipoll(struct cam_sim *sim)
2300{
2301	struct ahci_channel *ch = (struct ahci_channel *)cam_sim_softc(sim);
2302
2303	ahci_ch_intr(ch->dev);
2304}
2305