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