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