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