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